线程安全C#问题 [英] Thread Safety C# question

查看:70
本文介绍了线程安全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;

}





我的问题是isEnd是否是线程安全的? processStartThread是否有可能永远不会退出?我读了一本关于Java的书,它说代码不是线程安全的。想知道是否同样适用于C#

注意::这只是伪代码,即使它看起来像真正的c#代码。



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.

推荐答案

这段代码是线程安全的...因为所有对bool等原始类型的写入和读取都是原子的。虽然,你在while声明和while语句的正文中对 isEnd bool发生了两次检查...



还有其他问题可能会出现与编译器优化有关的问题,并且可能以一种呈现 isEnd 布尔值的任何更改的方式优化代码检查线程不可见。



查看C#中的volatile关键字,了解有关编译器优化的更多信息,以及如何在特定变量上避免它。



http ://msdn.microsoft.com/en-us/library/x13ttww7(v = vs.110).aspx [ ^ ]
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[^]


查看有关线程的这篇文章: http://www.albahari.com/threading/ [ ^ ]
Look at this article on threading: http://www.albahari.com/threading/[^]


这篇关于线程安全C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆