Question

I want to create an example that shows failure when using parallel loops. I am trying to make up an example, that shows in Prallel.For two threads might modify a common (non-thread-local) variables. For that, I write the following example, in which a thread assigns its number to a variable, and then we add a delay to see if any other thread will override this variable or not. In the output, it overriding never happens to me.

            Parallel.For(0, result.Length, ii =>
            {
                int threadNum = Thread.CurrentThread.ManagedThreadId;
                Thread.Sleep(10000);
                if (threadNum != Thread.CurrentThread.ManagedThreadId)
                    Console.WriteLine("threadNum = {0}, Thread.CurrentThread.ManagedThreadId = {1}", threadNum, Thread.CurrentThread.ManagedThreadId);
            });

One might argue that I am delaying all of the threads. So I add the delay to only one thread:

        int num = -1; 
        Parallel.For(0, result.Length, ii =>
        {
            if( num == -1)
                num = Thread.CurrentThread.ManagedThreadId;
            int threadNum = Thread.CurrentThread.ManagedThreadId;

            if (Thread.CurrentThread.ManagedThreadId == num) 
            {
                Console.WriteLine("num = {0}", num);
                Thread.Sleep(10);
            }
            if (threadNum != Thread.CurrentThread.ManagedThreadId)
                Console.WriteLine("threadNum = {0}, Thread.CurrentThread.ManagedThreadId = {1}", threadNum, Thread.CurrentThread.ManagedThreadId);

        });

Here it just remembers the first thread, and only delays that. Still I don't observe any over riding of the variable 'threadNum' by threads.

Any ideas?

Était-ce utile?

La solution

Your threadNum is declared in the closure, so each thread will have its own copy.

You could move it outside the closure.

Perhaps a better way to demonstrate concurrency issues would be to have multiple threads incrementing the same variable (that is defined in a scope accessible to all threads). The ++ operator is not atomic, so you are unlikely to have the end result be NumberOfThreads * NumberOfIterationsPerThread (assuming you start at zero).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top