Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
C#
static bool isEnd=false;


void Application()
{
Thread processStartThread=new Thread(new  ThreadStart(Process1));
processStart.Start();

Thread new userInputThread=new Thread(new ThreadStart(WaitForUserInput));
userInputThread.Start();
}

void Process1()
{

while(isEnd==false)
{
if(isEnd==true)
   break;
}


}


void WaitForUserInput()
{
//Wait for Input...Assumed that there is block of code below that makes isEnd=true with user //input

isEnd=true;

}


My question is whether isEnd is thread safe? Is there any chance that the processStartThread will never exit out ? I read a book on Java which said the code is not thread safe. Wanted to know if the same applied to C#
Note::This is meant to be only pseudo code even though it looks like real c# code.
Posted
Updated 4-Apr-13 16:15pm
v2

This code is thread safe... as all writes and reads to and from primitive types like bools are atomic. Although, you do have two checks on the isEnd bool happening here... in the while declaration, and in the body of the while statement.

There are other issues that can crop up concerning compiler optimizations, and possibly optimizing your code in a way that renders any changes to the isEnd boolean invisible to the checking thread.

Take a look at the volatile keyword in C# for more information on compiler optimization, and how to avoid it on specific variables.

http://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.110).aspx[^]
 
Share this answer
 
Comments
nitrous_007 5-Apr-13 20:25pm    
That is exactly what the Java book said..If there is compiler optimization etc, the computer might have 2 copies of isEnd and it might never be synchronized. Thanks I will look up compiler optimization.
Look at this article on threading: http://www.albahari.com/threading/[^]
 
Share this answer
 
Comments
nitrous_007 5-Apr-13 20:32pm    
Thank you. Appreciate your help!! I am going to buy some books on Threading also.
Clifford Nelson 5-Apr-13 20:43pm    
I would not bother. That paper should be as good as any book. There are also a lot of other articles, including on the codeproject site. One on the TPL is http://www.codeproject.com/Articles/152765/Task-Parallel-Library-1-of-n

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