线程安全和非线程安全的方法 [英] Thread safe and non thread safe methods

查看:144
本文介绍了线程安全和非线程安全的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我是多线程的新手。所以我的问题是



我们如何检查是否有任何方法需要线程安全,或者换句话说,如果代码是线程安全的话。例如



Hi Everyone,

I am very new to multithreading. So my question is

How can we check if any method needs threads safety or not, Or in other words if the code is thread safe or not. For e.g

int Foo ()
{
   int i = 10;
   i++;
   cout << i <<endl;
}





这是线程安全吗?如果是,为什么,如果不是为什么?



我们应该如何检查是否这个功能是否需要线程安全?



如果有人可以用一些简单的例子来解释,那将是非常值得注意的。



提前谢谢



Is this a thread safe? If yes why, if Not Why?

How should we check yes this function need thread safety or not?

It will be highly appreciable,If somebody can explain with few simple examples.

Thanks in advance

推荐答案

线程安全问题会出现在你有两个潜力的地方或多个线程(或进程或指令或......)可以同时具有对对象的并发访问权限,并且这些访问中的至少一个是写入。在你提供的代码示例中,没有与'i'的竞争条件,但可能有流对象访问cout。
Thread-safe issues will come up anywhere you have the potential for two or more threads (or processes or instructions or...) that can have concurrent access to an object at the same time, and at least one of those accesses is a ''write''. In the code example you provide, there is no race condition with ''i'' but there might be with the stream object that accesses cout.


线程安全是一个问题是函数使用共享资源(可以是从变量到磁盘上的文件的任何内容)。必须同步对这些共享资源的访问,才能将函数视为线程安全的。否则,竞争条件会出现并导致无法预料的行为。



现在,您的函数不是线程安全的,因为它使用cout,这是一个将输出流式传输到的对象安慰。这是一个共享资源,你应该同步它的访问权。
Thread safety is an issue is a function uses shared resources (that can be anything from a variable to a file on disk). Access to those shared resources must be synchronized, for a function to be considered thread-safe. Otherwise, race conditions can appear and lead to undexpected behavior.

Now, your function is not thread safe because it uses cout, which is an object that streams output to a console. This is a shared resource, and you should sync the access to it.


你好!



这是特定于实现的。 cout-stream可能是线程安全的,请询问您的编译器供应商,或阅读手册。然而,根据标准,没有要求它。



对于变量int i,它很容易。它是本地的线程开始int Foo(),它需要返回一个int btw。



Marius说其余的。线程安全意味着多个线程正在访问的资源,但只允许一个线程一次访问,需要保护。
Hello!

This is implementation-specific. It is possible that the cout-stream is threadsafe, ask your compiler-vendor, or read the manual. Nevertheless there is no requirement for it to be, by the standard.

For the variable "int i" it is easy. It is local to the thread starting "int Foo()", which needs to return an int btw.

Marius said the rest. Thread-Safety means that ressources being in access by multiple threads but are only allowed to be in access by one single thread at a time need to be secured.


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

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