Click here to Skip to main content
15,888,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have written following code to update a variable using multiple thread

C#
namespace InterlockedApp
{
    class Program
    {
        static void Main(string[] args)
        {
            MyNum n = new MyNum();
            for (int i = 0; i < 10; i++)
            {
            for(int j=0;j<100;j++)
            {
                Thread t = new Thread(new ThreadStart(n.AddOne));
                t.Start();
            }
                Console.WriteLine(n.num);
            }
        }
    }
    public class MyNum
    {
        public int num = 1;
        public void AddOne()
        {
                Interlocked.Increment(ref num);

        }

    }
}


To make sure the value is not overwritten, I am using Interlocked. Based on the the out put should be
100
200
300
..
.
.
1000

But what I am getting is
100
200
300
499
501
...

1001

Everytime you run the program, output is different from ideal...

Any idea what is wrong with the code?
Posted

This is perfectly expected and even desirable result.

It does not depend on how many cores you're running, the same effect you can expect even on a single-core single-CPU computer. It looks like you don't want parallel execution in this case, why using thread then?

If you explain your ultimate goal and the idea on what you want to get from concurrent execution, it can get further advice. In real life, most more or less advanced applications require concurrent scenarios.

—SA
 
Share this answer
 
Comments
Olivier Levrey 9-Mar-11 4:38am    
I agree. 5.
Sergey Alexandrovich Kryukov 9-Mar-11 13:54pm    
Thank you, Olivier,
--SA
rajeshmulchandani 9-Mar-11 4:43am    
Hi SAKryukov. Thanks for the response. If this is as expected, then how do I make sure in parallel processing that the state info (in this case variable num) is not corrupted i.e make it thread safe?
Sergey Alexandrovich Kryukov 9-Mar-11 13:54pm    
It depends how you use it in both threads. In general case, if you access any data, you need to sandwich access to this data by "lock(lockObject)", where lockObject is the same for the same data structures for different threads. In more general case, if you mostly read and more rarely write, you better use System.Threading.ReaderWriterLockSlim. I'll need to post whole different answer to explain that.
--SA
rajeshmulchandani 10-Mar-11 8:42am    
Thanks SAKryukov
If you want the output to display 100, 200, ... as you explained, then you need to wait for all threads to finish before printing the output, then start the next ones, and so on.

SA is right: it means you don't need theads at all in your scenario.

By the way, you should also initialize num to 0 and not 1...
 
Share this answer
 
v2
Comments
rajeshmulchandani 9-Mar-11 5:07am    
Thanks Olivier. I may sound thick here but according to this article http://msdn.microsoft.com/en-us/library/5kczs5b5%28v=VS.90%29.aspx, shouldn't the output be ideal even if I dont wait for all threads? By adding t.Join(); in above code I am getting expected result but in that case main thread will have to wait for all other threads to finish. What I am trying to replicate is a application running on multiple threads but sharing a common resource. The resource could be a file. Any help would be greatly appreciated.
Olivier Levrey 9-Mar-11 5:19am    
There is a big difference between your code and the example provided on the link: you are printing the threads output from the main thread. If you want to share data between threads, you need to use synchronization mechanisms (Thread.Join, ManualResetEvent, AutoResetEvent, Mutex, Semaphore, and more...). The mechanism to use depends on your application. Your question about sharing a common resource is too generic. If you give details about what you want to do with your shared file (or anyting else), then we will be able to help.
rajeshmulchandani 9-Mar-11 5:09am    
thinking about it, I think you are right. I will have to wait for the threads to finish by using t.Join();

Many thanks
Olivier Levrey 9-Mar-11 5:21am    
OK good then.
rajeshmulchandani 9-Mar-11 5:42am    
Thanks Olivier. "Thread Synchronization" is what I was missing and Thread.Join does the trick.
Many thanks once again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900