Search Results

Search found 1950 results on 78 pages for 'james watt'.

Page 14/78 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How can I pass an array of floats to the fragment shader using textures?

    - by James
    I want to map out a 2D array of depth elements for the fragment shader to use to check depth against to create shadows. I want to be able to copy a float array into the GPU, but using large uniform arrays causes segfaults in openGL so that is not an option. I tried texturing but the best i got was to use GL_DEPTH_COMPONENT glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, smap); Which doesn't work because that stores depth components (0.0 - 1.0) which I don't want because I have no idea how to calculate them using the depth value produced by the light sources MVP matrix multiplied by the coordinate of each vertex. Is there any way to store and access large 2D arrays of floats in openGL?

    Read the article

  • Cost effective way to provide static media content

    - by james
    I'd like to be able to deliver around 50MB of static content, either in about 30 individual files up to 10MB or grouped into 3 compressed files, around 5k to 20k times a day. Ideally I'd like to put some sort of very basic security around providing the data to ensure that a request is from the expected source, but if tossing the security for a big reduction in price is possible then it's an option. Does anyone have any suggestions other than what I've found: Google AppEngine is $0.12/GB & I believe has a file size limit of 10MB so I'd have to break the data up a bit. So a rough calculation would seem to be that this would cost me about $30 to $120 a day. Or I've seen something like what seems to be just public static content delivery with no type of logic capabilities like Usenet.nl at what I think calculates to about $0.025/GB which would cost me about $6 to $25 a day. Any idea if I'm going about these calculations right & if there might be a better option for just static content on a decently high volume delivery? Again some basic security would be great but if cost is greatly reduced without it then I'm up for that.

    Read the article

  • Creating a Website Without a Framework [closed]

    - by James Jeffery
    I've been using PHP Frameworks for so long that I've actually forgot the "best practices" for create websites without one. Usually I will use Symfony, or more recently I've been using Laravel. A client wants a very simple website, but with certain parts of it dynamic. Due to the nature of the site using Wordpress, or a Framework, is out of the question. I'm a sucker for priding myself on my code, but I feel like I'm asking such a basic question that it's killing me to ask. But, what are the best practices for creating websites without a Framework? I like to live by the K.I.S.S (Keep It Simple Stupid!) method of thinking. So, my idea was to just create the .php pages that are required, do any page processing or database interaction on that page, then have the HTML below the closing PHP tag. I would have any helpers/functions in a functions.php file. This is what I remember doing way before I was using Frameworks, and to me it seems like a very old school way of doing things. I've not created a site without a Framework for literally 2+ years, so I've lost my way with the basics. Any advice would be greatly appreciated.

    Read the article

  • Thread safe GUI programming

    - by James
    I have been programming Java with swing for a couple of years now, and always accepted that GUI interactions had to happen on the Event Dispatch Thread. I recently started to use GTK+ for C applications and was unsurprised to find that GUI interactions had to be called on gtk_main. Similarly, I looked at SWT to see in what ways it was different to Swing and to see if it was worth using, and again found the UI thread idea, and I am sure that these 3 are not the only toolkits to use this model. I was wondering if there is a reason for this design i.e. what is the reason for keeping UI modifications isolated to a single thread. I can see why some modifications may cause issues (like modifying a list while it is being drawn), but I do not see why these concerns pass on to the user of the API. Is there a limit imposed by an operating system? Is there a good reason these concerns are not 'hidden' (i.e. some form of synchronization that is invisible to the user)? Is there any (even purely conceptual) way of creating a thread safe graphics library, or is such a thing actually impossible? I found this http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness which seems to describe GTK differently to how I understood it (although my understanding was the same as many people's) How does this differ to other toolkits? Is it possible to implement this in Swing (as the EDT model does not actually prevent access from other threads, it just often leads to Exceptions)

    Read the article

  • Hilarious

    - by James Luetkehoelter
    I don't know how many of you know about this site, but it raises my spirits on a daily basis. I found today's entry oddly familiar... http://thedailywtf.com/Articles/sp_getNothing.aspx Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!...(read more)

    Read the article

  • How to handle mutiple API calls using javascript/jquery

    - by James Privett
    I need to build a service that will call multiple API's at the same time and then output the results on the page (Think of how a price comparison site works for example). The idea being that as each API call completes the results are sent to the browser immediately and the page would get progressively bigger until all process are complete. Because these API calls may take several seconds each to return I would like to do this via javascript/jquery in order to create a better user experience. I have never done anything like this before using javascript/jquery so I was wondering if there was any frameworks/advice that anyone would be willing to share.

    Read the article

  • Revert F3 and F4 behavior in byobu?

    - by James Zimmerman II
    With a fresh 12.04 installation of Ubuntu, byobu's interpretation of the function keys seems to have changed. F3 and F4 will still change the active tab on the current session, but it changes it for all connections. Previously, if you have two active connections to the same user (same session) with User 1 on shell 0/tab 0 and User 2 on shell 0/tab 0, when User 2 pressed F3 , they would be changed to tab 1 while User 1 would remain on tab 0. With the latest version in 12.04, when User 2 presses F3, all connected users are moved to shell 1/tab 1. Is there any way to re-enable the old behavior? I have looked at the /etc/byobu directory and only found backend and socketdir files there. Toggling backend between tmux and screen did not seem to render any difference. Anyone know what, if any, configuration option exist to control this?

    Read the article

  • How can I easily retab html files according to some sane default?

    - by James
    I have some html files that I'd like to retab that look like this: <header> <div class="wrapper"> <img src="images/logo.png"> <div class="userbox"> <div class="welcome">Welcome Andy!</div> <div class="blackbox"> <ul> <li><a href="#">Invite Friends</a></li> <li><a href="#">My Account</a></li> <li><a href="#">Cart</a></li> <li><a href="#">Sign Out</a></li> </ul> </div> </div> </div> </header> And I want them to look something like this: <header> <div class="wrapper"> <img src="images/logo.png"> <div class="userbox"> <div class="welcome">Welcome Andy!</div> <div class="blackbox"> <ul> <li><a href="#">Invite Friends</a></li> <li><a href="#">My Account</a></li> <li><a href="#">Cart</a></li> <li><a href="#">Sign Out</a></li> </ul> </div> </div> </div> </header> Or some sane default. What's the easiest way to go about doing this from the terminal in ubuntu for all of the html files in the current directory?

    Read the article

  • Compiling kernal problem

    - by James
    Hi, I have a hp pavilion dm3t with intel HD graphics running ubuntu 10.10 64 bit. I'm trying to compile and install a patched kernel according to this, https://launchpad.net/~kamalmostafa/+archive/linux-kamal-mjgbacklight So I downloaded the tarball from here (linked to from the page above): http://kernel.ubuntu.com/git?p=kamal/ubuntu-maverick.git;a=shortlog;h=refs/heads/mjg-backlight I untar'd it to a directory, entered the directory and did: make defconfig which was successful, so I did: make which seemed to work fine until it gave these errors: ubuntu/ndiswrapper/iw_ndis.c:1966: error: unknown field ‘num_private’ specified in initializer ubuntu/ndiswrapper/iw_ndis.c:1966: warning: initialization makes pointer from integer without a cast ubuntu/ndiswrapper/iw_ndis.c:1967: error: unknown field ‘num_private_args’ specified in initializer ubuntu/ndiswrapper/iw_ndis.c:1967: warning: excess elements in struct initializer ubuntu/ndiswrapper/iw_ndis.c:1967: warning: (near initialization for ‘ndis_handler_def’) ubuntu/ndiswrapper/iw_ndis.c:1970: error: unknown field ‘private’ specified in initializer ubuntu/ndiswrapper/iw_ndis.c:1970: warning: initialization makes integer from pointer without a cast ubuntu/ndiswrapper/iw_ndis.c:1970: error: initializer element is not computable at load time ubuntu/ndiswrapper/iw_ndis.c:1970: error: (near initialization for ‘ndis_handler_def.num_standard’) ubuntu/ndiswrapper/iw_ndis.c:1971: error: unknown field ‘private_args’ specified in initializer ubuntu/ndiswrapper/iw_ndis.c:1971: warning: initialization from incompatible pointer type make[2]: *** [ubuntu/ndiswrapper/iw_ndis.o] Error 1 make[1]: *** [ubuntu/ndiswrapper] Error 2 make: *** [ubuntu] Error 2 How can I compile and install this kernel successfully? I'm new to this and would appreciate any help.

    Read the article

  • Printing with Lacie Lightscribe requires root privileges

    - by James
    I have installed Lacie Lightscribe software on Ubuntu 12.04. Everything seems to be fine, the drive is detected, the proper media is detected, but when I click print I get the message "Printing Requires Root Privileges". I am the main (administrator) account on this computer, part of the sudo group and I cannot seem to find an answer to this dilemna in plain english. I've seen some apparently relevant posts which say things like "check whether the files /usr/4L/4L-gui and /usr/4L/4L-cli have any setuid-bits set. If so, remove them" but I need more detailed step-by-step instructions than that, please. Is there anyone who knows how to solve this?

    Read the article

  • Examples of Liskov Substitution

    - by james lewis
    I'm facilitating a session next week on the Liskov Substitution Principle and I was wondering if anyone had any examples of violations 'from the trenches'? I'm looking for something other than uncle Bob's rectangle - square problem and the persistent set problem he talks about in A-PPP (although that is a great example). So far I'm using the example of a (very simple) List and an IndexedList as the 'correct' use of inheritance. And the addition of a Set to this hierarchy as a violation (as a Set is distinct; strengthening the pre condition of the Add method). I've also taken this great example and it's solution from this question Both those examples are great but I'm looking for something more subtle and harder to spot. So far I've come up with nothing so if you've got a great, subtle example post it up. Also, any metaphors you've come across that helped you understand LSP would be really useful too.

    Read the article

  • Are there Know issues with Ubuntu 11 and socket 1155? acpi=off

    - by James
    Since building my new system I cant get Ubuntu (or any other flavor of Linux) to "run" properly. To boot the live cd I have to "F6" and turn off acpi or the screen halts at a black screen with "boot stuff" written above the blinking curser. When installed I can only boot if I enter repair mode from Grub menu then once in repair mode I choose Boot Normally and it boots to the desktop. Once on the desktop I can "click" (with the mouse) only on one thing...like firefox or "desktop appearance" and the mouse no longer "clicks" on anything else ...its like the computer freezes but the mouse still moves. I end up using the reset button to restart the computer. I was able to update when prompted to do so....but at the end of the update I could not "click" the "finish" and had to use the manual reset button. I have run Ubuntu since v 8... My system specs are: intel i7 2600k ...Graphics disabled in bios... Asus p8z68-v pro.... 16G Kingston HyperX.... 2 EVGA GTX 570 in SLI.... Mouse is a simple Logitech usb Wireless. Ubuntu installed on secondary sata drive.

    Read the article

  • Comparing Dates in Oracle Business Rule Decision Tables

    - by James Taylor
    I have been working with decision tables for some time but have never had a scenario where I need to compare dates. The use case was to check if a persons membership had expired. I didn't think much of it till I started to develop it. The first trap I feel into was trying to create ranges and bucket sets. The other trap I fell into was not converting the date field to a complete date. This may seem obvious to most people but my Google searches came up with nothing so I thought I would create a quick post. I assume everyone knows how to create a decision table so I'm not going to go through those steps. The prerequisite for this post is to have a decision table with a payload that has a date field. This filed must have the date in the following format YYYY-MM-DDThh:mm:ss. Create a new condition in your decision table Right-click on the condition to edit it and select the expression builder In the expression builder, select the Functions tab. Expand the CurrentDate file and select date, and click Insert Into Expression button. In the Expression Builder you need to create an expression that will return true or false, add the operation <= after the CurrentDate.date In my scenario my date field is memberExpire, Navigate to your date field and expand, select toGregorianCalendar(). Your expression will look something like this, click OK to get back to the decision table Now its just a matter of checking if the value is true or false. Simple when you know how :-)

    Read the article

  • How do I change Firefox's `about:config` from a shell script?

    - by James Haigh
    On of the first things I do when first using a fresh Firefox profile, is to set browser.urlbar.trimURLs to false (which really should be changeable though ‘Preferences’ or should have remained default), and to change the search and homepage defaults to DuckDuckGo. Currently I manually go to about:config, click through the angry warning message, and search for the keys (which unlike in DConf Editor, aren't even organised). So I would like to know how to read and write these keys from the command-line so that I can add these tweaks to my customisations script.

    Read the article

  • Package linux-headers-3.7.0-999 is not installed

    - by James Ward
    When trying to install the three amd64 debs for the 3.7.0 kernel from: http://kernel.ubuntu.com/~kernel-ppa/mainline/daily/2012-10-22-quantal/ I get this error: dpkg: dependency problems prevent configuration of linux-headers-3.7.0-999-generic: linux-headers-3.7.0-999-generic depends on linux-headers-3.7.0-999; however: Package linux-headers-3.7.0-999 is not installed. It installs and works correctly but leaves me with broken packages in Synaptic. Is this just a bug with how Ubuntu is packaging these latest debs? Or am I doing something wrong?

    Read the article

  • Change Logging Level for SOA 11g

    - by James Taylor
    I’m sure there are many blogs out there that have this solution. But I seem to get asked this question a lot so I thought I would post it here for my convenience. Login to Enterprise Manager, e.g. http://localhost:7001/em Expand the SOA folder and right-click the soa-infra(soa_server1) folder and select Logs – Log Configuration Navigate to the component you want to monitor and change the log level. It is possible to change at a parent level if required It is not recommended that you set the level to FINIEST at a parent level as it will generate a lot of logging. Make sure you apply the change to take affect. Simple as that.

    Read the article

  • A case for not installing your own software

    - by James Gentsch
    This week I watched some of the Oracle Open World presentations (from the comfort of my Oracle office) and happened on some of Larry Ellison’s comments about cloud computing and engineered systems.  Larry said he sees the move to these as analogous to the moves made by the original adopters of electricity.  The argument goes that the first consumers of electricity had to set up their own power plant.  Then, as the market and infrastructure for electricity matured, power consumers moved from using their own personal power plant to purchasing power from another entity that was focused on power production as their primary product. In the end this was a cheaper and more reliable solution. Now, there are lots of compelling reasons to be looking very seriously at cloud computing and engineered systems for enterprise application deployment.  However, speaking as a software developer of enterprise applications, the part of this that I really love (besides Larry’s early electricity adopter analogy) is that as a mode of application deployment it provides me and my customers a consistent environment in which the applications I am providing will be run.  This cuts way down on the environmental surprises that consistently lead to the hated “well, it works here” situation with the support desk. And just to be clear, I think I hate this situation more than my clients, who I think are happy that at least it is working somewhere.  I hate this because when a problem happens, and let’s face it customers are not wasting their time calling in easy problems, we are seriously disabled when we cannot reproduce the issue which is triggered by something unforeseen in the environment where the application is running.  This situation is incredibly frustrating and an all too often occurrence. I look selfishly forward to cloud computing and engineered systems dramatically reducing the occurrence of problems triggered by unforeseen environmental situations in the software I am responsible for.  I think this is an evolutionary game changer that will be a huge benefit to the reliability and consistent performance of the software for my customers, and may make “well, it works here” a well forgotten phase for future software developers. It may even impact the stress squeeze toy industry.  Well, maybe at least for my group.

    Read the article

  • C# Toolbox: Debug-able, Self-Installable Windows Service Template Redux

    - by James Michael Hare
    I had written a pair of posts before about creating a debug-able and self-installing windows service template in C#.  This is a template I began creating to ease creating windows services and to take some of the mundane tasks out of the coding effort.  The original posts were here: C# Windows Services (1 of 2) - Debug-able Windows Services C# Windows Services (2 of 2) - Self-Installing Windows Services But at the time, though I gave the code samples I didn't have a downloadable for of the template on the blog.  After getting many requests for the actual source, I zipped it up and am posting it with this blog entry.  Click on the link below to download the archive.  The password on the archive is, imaginatively enough, password.  Hope you enjoy and please feel free to comment and suggest changes! Debug-able, Self-Installing Windows Service Template download Enjoy! Tweet Technorati Tags: C#,Windows Service,Toolbox

    Read the article

  • Create an ad-hoc connection that looks like a wifi connection from a router

    - by James
    I have a Vizio tablet (running a modified version of Android 2.3.2) which, for some reason or another, refuses to list Windows ad-hoc wifi connections on it's wifi connection screen. It can connect to wifi networks served from a normal router, but the wireless bit of my home router is broken, so I'd like to share the internet connection through my laptop's wifi card until the new router arrives. Is it possible to create an ad-hoc network in Ubuntu that looks like a normal wireless network to my tablet?

    Read the article

  • How do you update copyright notices?

    - by James
    So now it's 2011, and as I carry on coding on our active projects it's time to update some copyright notices. eg. Copyright Widgets Ltd 2010 to Copyright Widgets Ltd 2010, 2011 My question is when do you update the copyright notices? Do you change the notice in the head of a file the first time you work on that file? Since a module is one piece of code consisting of many files that work together, do you update all notices in that module when you change a single file in that module? Since a program is one piece of code (maybe consisting of many modules), do you update all notices in that program when you change a single file in that program? Or do you just go through and change en-mass over your morning coffee on the grounds your about to start programming and updateing things?

    Read the article

  • A Trio of Presentations: Little Wonders, StyleCop, and LINQ/Lambdas

    - by James Michael Hare
    This week is a busy week for me.  First of all I’m giving another presentation on a LINQ/Lambda primer for the rest of the developers in my company.  Of Lambdas and LINQ View more presentations from BlackRabbitCoder Then this Saturday the 25th of June I’ll be reprising my Little Wonders presentation for the Kansas City Developers Camp.  If you are in the area I highly recommend attending and seeing the other great presentations as well.  Their link is here. Little Wonders View more presentations from BlackRabbitCoder Finally, this Monday the 27th I’ll be speaking at the Saint Louis .NET Users group, giving my Automating Code Standards Using StyleCop and FxCop presentation.  If you are in the Saint Louis area stop by!  There’s two other simultaneous presentations as well if they’re more suited to your interests.  The link for the SLDNUG is here. Automating C# Coding Standards using StyleCop and FxCop View more presentations from BlackRabbitCoder Tweet Technorati Tags: C#,.NET,LINQ,Lambda,StyleCop,FxCop,Little Wonders

    Read the article

  • Why use an OO approach instead of a giant "switch" statement?

    - by James P. Wright
    I am working in a .Net, C# shop and I have a coworker that keeps insisting that we should use giant Switch statements in our code with lots of "Cases" rather than more object oriented approaches. His argument consistently goes back to the fact that a Switch statement compiles to a "cpu jump table" and is therefore the fastest option (even though in other things our team is told that we don't care about speed). I honestly don't have an argument against this...because I don't know what the heck he's talking about. Is he right? Is he just talking out his ass? Just trying to learn here.

    Read the article

  • disk space error, cant use internet

    - by James
    after trying to install drivers using sudo apt-get update && sudo apt-get upgrade, im faced with a message saying no space left on device, i ran disk usage analyzer as root and there was three folders namely, main volume, home folder, and my 116gb hard drive (which is practically empty) yet both other folders are full, which is stopping me installing drivers because of space, how do i get ubuntu to use this space on my hard drive? its causing problems because i cant gain access to the internet as i cant download drivers when i havnt got enough space, this happens every time i try it

    Read the article

  • C#/.NET Little Wonders: Interlocked CompareExchange()

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Two posts ago, I discussed the Interlocked Add(), Increment(), and Decrement() methods (here) for adding and subtracting values in a thread-safe, lightweight manner.  Then, last post I talked about the Interlocked Read() and Exchange() methods (here) for safely and efficiently reading and setting 32 or 64 bit values (or references).  This week, we’ll round out the discussion by talking about the Interlocked CompareExchange() method and how it can be put to use to exchange a value if the current value is what you expected it to be. Dirty reads can lead to bad results Many of the uses of Interlocked that we’ve explored so far have centered around either reading, setting, or adding values.  But what happens if you want to do something more complex such as setting a value based on the previous value in some manner? Perhaps you were creating an application that reads a current balance, applies a deposit, and then saves the new modified balance, where of course you’d want that to happen atomically.  If you read the balance, then go to save the new balance and between that time the previous balance has already changed, you’ll have an issue!  Think about it, if we read the current balance as $400, and we are applying a new deposit of $50.75, but meanwhile someone else deposits $200 and sets the total to $600, but then we write a total of $450.75 we’ve lost $200! Now, certainly for int and long values we can use Interlocked.Add() to handles these cases, and it works well for that.  But what if we want to work with doubles, for example?  Let’s say we wanted to add the numbers from 0 to 99,999 in parallel.  We could do this by spawning several parallel tasks to continuously add to a total: 1: double total = 0; 2:  3: Parallel.For(0, 10000, next => 4: { 5: total += next; 6: }); Were this run on one thread using a standard for loop, we’d expect an answer of 4,999,950,000 (the sum of all numbers from 0 to 99,999).  But when we run this in parallel as written above, we’ll likely get something far off.  The result of one of my runs, for example, was 1,281,880,740.  That is way off!  If this were banking software we’d be in big trouble with our clients.  So what happened?  The += operator is not atomic, it will read in the current value, add the result, then store it back into the total.  At any point in all of this another thread could read a “dirty” current total and accidentally “skip” our add.   So, to clean this up, we could use a lock to guarantee concurrency: 1: double total = 0.0; 2: object locker = new object(); 3:  4: Parallel.For(0, count, next => 5: { 6: lock (locker) 7: { 8: total += next; 9: } 10: }); Which will give us the correct result of 4,999,950,000.  One thing to note is that locking can be heavy, especially if the operation being locked over is trivial, or the life of the lock is a high percentage of the work being performed concurrently.  In the case above, the lock consumes pretty much all of the time of each parallel task – and the task being locked on is relatively trivial. Now, let me put in a disclaimer here before we go further: For most uses, lock is more than sufficient for your needs, and is often the simplest solution!    So, if lock is sufficient for most needs, why would we ever consider another solution?  The problem with locking is that it can suspend execution of your thread while it waits for the signal that the lock is free.  Moreover, if the operation being locked over is trivial, the lock can add a very high level of overhead.  This is why things like Interlocked.Increment() perform so well, instead of locking just to perform an increment, we perform the increment with an atomic, lockless method. As with all things performance related, it’s important to profile before jumping to the conclusion that you should optimize everything in your path.  If your profiling shows that locking is causing a high level of waiting in your application, then it’s time to consider lighter alternatives such as Interlocked. CompareExchange() – Exchange existing value if equal some value So let’s look at how we could use CompareExchange() to solve our problem above.  The general syntax of CompareExchange() is: T CompareExchange<T>(ref T location, T newValue, T expectedValue) If the value in location == expectedValue, then newValue is exchanged.  Either way, the value in location (before exchange) is returned. Actually, CompareExchange() is not one method, but a family of overloaded methods that can take int, long, float, double, pointers, or references.  It cannot take other value types (that is, can’t CompareExchange() two DateTime instances directly).  Also keep in mind that the version that takes any reference type (the generic overload) only checks for reference equality, it does not call any overridden Equals(). So how does this help us?  Well, we can grab the current total, and exchange the new value if total hasn’t changed.  This would look like this: 1: // grab the snapshot 2: double current = total; 3:  4: // if the total hasn’t changed since I grabbed the snapshot, then 5: // set it to the new total 6: Interlocked.CompareExchange(ref total, current + next, current); So what the code above says is: if the amount in total (1st arg) is the same as the amount in current (3rd arg), then set total to current + next (2nd arg).  This check and exchange pair is atomic (and thus thread-safe). This works if total is the same as our snapshot in current, but the problem, is what happens if they aren’t the same?  Well, we know that in either case we will get the previous value of total (before the exchange), back as a result.  Thus, we can test this against our snapshot to see if it was the value we expected: 1: // if the value returned is != current, then our snapshot must be out of date 2: // which means we didn't (and shouldn't) apply current + next 3: if (Interlocked.CompareExchange(ref total, current + next, current) != current) 4: { 5: // ooops, total was not equal to our snapshot in current, what should we do??? 6: } So what do we do if we fail?  That’s up to you and the problem you are trying to solve.  It’s possible you would decide to abort the whole transaction, or perhaps do a lightweight spin and try again.  Let’s try that: 1: double current = total; 2:  3: // make first attempt... 4: if (Interlocked.CompareExchange(ref total, current + i, current) != current) 5: { 6: // if we fail, go into a spin wait, spin, and try again until succeed 7: var spinner = new SpinWait(); 8:  9: do 10: { 11: spinner.SpinOnce(); 12: current = total; 13: } 14: while (Interlocked.CompareExchange(ref total, current + i, current) != current); 15: } 16:  This is not trivial code, but it illustrates a possible use of CompareExchange().  What we are doing is first checking to see if we succeed on the first try, and if so great!  If not, we create a SpinWait and then repeat the process of SpinOnce(), grab a fresh snapshot, and repeat until CompareExchnage() succeeds.  You may wonder why not a simple do-while here, and the reason it’s more efficient to only create the SpinWait until we absolutely know we need one, for optimal efficiency. Though not as simple (or maintainable) as a simple lock, this will perform better in many situations.  Comparing an unlocked (and wrong) version, a version using lock, and the Interlocked of the code, we get the following average times for multiple iterations of adding the sum of 100,000 numbers: 1: Unlocked money average time: 2.1 ms 2: Locked money average time: 5.1 ms 3: Interlocked money average time: 3 ms So the Interlocked.CompareExchange(), while heavier to code, came in lighter than the lock, offering a good compromise of safety and performance when we need to reduce contention. CompareExchange() - it’s not just for adding stuff… So that was one simple use of CompareExchange() in the context of adding double values -- which meant we couldn’t have used the simpler Interlocked.Add() -- but it has other uses as well. If you think about it, this really works anytime you want to create something new based on a current value without using a full lock.  For example, you could use it to create a simple lazy instantiation implementation.  In this case, we want to set the lazy instance only if the previous value was null: 1: public static class Lazy<T> where T : class, new() 2: { 3: private static T _instance; 4:  5: public static T Instance 6: { 7: get 8: { 9: // if current is null, we need to create new instance 10: if (_instance == null) 11: { 12: // attempt create, it will only set if previous was null 13: Interlocked.CompareExchange(ref _instance, new T(), (T)null); 14: } 15:  16: return _instance; 17: } 18: } 19: } So, if _instance == null, this will create a new T() and attempt to exchange it with _instance.  If _instance is not null, then it does nothing and we discard the new T() we created. This is a way to create lazy instances of a type where we are more concerned about locking overhead than creating an accidental duplicate which is not used.  In fact, the BCL implementation of Lazy<T> offers a similar thread-safety choice for Publication thread safety, where it will not guarantee only one instance was created, but it will guarantee that all readers get the same instance.  Another possible use would be in concurrent collections.  Let’s say, for example, that you are creating your own brand new super stack that uses a linked list paradigm and is “lock free”.  We could use Interlocked.CompareExchange() to be able to do a lockless Push() which could be more efficient in multi-threaded applications where several threads are pushing and popping on the stack concurrently. Yes, there are already concurrent collections in the BCL (in .NET 4.0 as part of the TPL), but it’s a fun exercise!  So let’s assume we have a node like this: 1: public sealed class Node<T> 2: { 3: // the data for this node 4: public T Data { get; set; } 5:  6: // the link to the next instance 7: internal Node<T> Next { get; set; } 8: } Then, perhaps, our stack’s Push() operation might look something like: 1: public sealed class SuperStack<T> 2: { 3: private volatile T _head; 4:  5: public void Push(T value) 6: { 7: var newNode = new Node<int> { Data = value, Next = _head }; 8:  9: if (Interlocked.CompareExchange(ref _head, newNode, newNode.Next) != newNode.Next) 10: { 11: var spinner = new SpinWait(); 12:  13: do 14: { 15: spinner.SpinOnce(); 16: newNode.Next = _head; 17: } 18: while (Interlocked.CompareExchange(ref _head, newNode, newNode.Next) != newNode.Next); 19: } 20: } 21:  22: // ... 23: } Notice a similar paradigm here as with adding our doubles before.  What we are doing is creating the new Node with the data to push, and with a Next value being the original node referenced by _head.  This will create our stack behavior (LIFO – Last In, First Out).  Now, we have to set _head to now refer to the newNode, but we must first make sure it hasn’t changed! So we check to see if _head has the same value we saved in our snapshot as newNode.Next, and if so, we set _head to newNode.  This is all done atomically, and the result is _head’s original value, as long as the original value was what we assumed it was with newNode.Next, then we are good and we set it without a lock!  If not, we SpinWait and try again. Once again, this is much lighter than locking in highly parallelized code with lots of contention.  If I compare the method above with a similar class using lock, I get the following results for pushing 100,000 items: 1: Locked SuperStack average time: 6 ms 2: Interlocked SuperStack average time: 4.5 ms So, once again, we can get more efficient than a lock, though there is the cost of added code complexity.  Fortunately for you, most of the concurrent collection you’d ever need are already created for you in the System.Collections.Concurrent (here) namespace – for more information, see my Little Wonders – The Concurent Collections Part 1 (here), Part 2 (here), and Part 3 (here). Summary We’ve seen before how the Interlocked class can be used to safely and efficiently add, increment, decrement, read, and exchange values in a multi-threaded environment.  In addition to these, Interlocked CompareExchange() can be used to perform more complex logic without the need of a lock when lock contention is a concern. The added efficiency, though, comes at the cost of more complex code.  As such, the standard lock is often sufficient for most thread-safety needs.  But if profiling indicates you spend a lot of time waiting for locks, or if you just need a lock for something simple such as an increment, decrement, read, exchange, etc., then consider using the Interlocked class’s methods to reduce wait. Technorati Tags: C#,CSharp,.NET,Little Wonders,Interlocked,CompareExchange,threading,concurrency

    Read the article

  • Remote Working & Relocation

    - by James Burgess
    Sorry if this question is a duplicate, I did some extensive searching and found nothing on quite the same topic (though a couple on partially-overlapping topics). Recently, whilst on holiday in Munich, Germany, I was taken aback by the sheer number of programming-related posts available in the city that I easily qualify for (both in terms of knowledge, and experience). The advertised working environments seemed good and the pay seemed to be at least as good as what I'd expect here in the UK. Probably 80% of the advertisements I saw on the underground were for IT-related jobs, and a good 60% of those I was easily qualified for. At the moment, I work as a freelancer mostly on web and small software projects, but seeing the vast availability of jobs in Munich versus my local area has me thinking about remote working. I'm unable to relocate for a job for the next 3 years (my wife has a contract to continue being a doctor at her current hospital for that time) but would almost certainly be open to it after that (after all, my wife and I both love Munich). In the meanwhile, I would be very interested in remote-working. So, my question is thus do companies ever take on remote workers (even with semi-frequent trips to the office) from abroad, with a view to later relocation? And, if so, how do you go about broaching the topic with a recruiter when getting in contact about a job posting? Language isn't a barrier for me, here, as 90% of the jobs I've looked up in Munich don't require German speakers (seems they have a big recruiting market abroad). I'm also under no illusions about the disadvantages of remote working, but I'm more interested in the viability of the scenario rather than the intricacies (at least at this point). I'd really appreciate any contributions, especially from those who have experience with working in such a scenario!

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >