long val = amount+1; amount = val;
using System; using System.Threading; namespace ThreadTest { class Program { static object pause = new object(); static object amountlock = new object(); static long amount = 0; static long count = 10000000; static void MyThread() { // Wait until we can go lock (pause) { } // Add to the amount for (int i = 0; i < count; i++) { //lock (amountlock) // Uncomment this to see what difference it makes { long val = amount+1; amount = val; } } } static void Main(string[] args) { Thread[] threads = new Thread[10]; // Start the threads lock (pause) // lock them so they start simultaneously { for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ThreadStart(MyThread)); threads[i].Start(); } } // Wait for them all to finish for (int i = 0; i < threads.Length; i++) threads[i].Join(); // Done Console.WriteLine("Total sum: {0} (should be {1})", amount, count * threads.Length); } } }
Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.
(Comp Sci, Hons - UTS)
Software Developer (Freelancer / Contractor) in Australia.
I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!
Get in touch:
[email protected]
github.com/chrishulbert
linkedin