Related Tags:
C# C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java. Learn More, Multithreading Multithreading is a technique by which a single set of code can be used by several processors at different stages of execution. Learn More, Task Parallel Library (TPL) The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. Learn More, race condition A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly. Learn More,

How to maintain consistency in a variable that is shared among several threads in Task parallel library?

Description:I am using task parallel library to run a for loop on all of my CPU cores, but I am just thinking that the resultant of all the operation performed is not going to be what I want? Is there a way to perform operations on a class level variable shared with multiple threads so that the answer of Parallel.For() doesn't return inconsistent value!
For learning purpose I have written a simple code chunk as follows which is always returning less than 10000000


int total = 0;
Parallel.For(0, 10000000, (i) =>
{
total++;
});
Console.WriteLine(total);
Console.ReadKey();

Posted by: | Posted on: Mar 15, 2019

1 answers

Replies

3

I assume that you wrote this code for learning the concept only otherwise its not a very good example to use multithreading but what I understand from your code is that your total variable here having a race condition to avoid this you can simply use Interlocked's class add method which will access your global variable in a thread safe manner so your code will look like the following one.

int total = 0;
Parallel.For(0, 10000000, (i) =>
{
//total++;
Interlocked.Add(ref total, 1)
});
Console.WriteLine(total);
Console.ReadKey();

Replied by: | Replied on: Mar 19, 2019



Reply
×

Code block Hyperlink bold Quotes block Upload Images

Preview