我是 C++
的新手,但我需要以多线程方式编写一些代码。在下面的代码中,如果 Increase_value()
被多个线程调用,确保 Print_Value()
打印 ID 的最有效方法是什么
Increase_value()
最初增加的值。换句话说,如何确保在运行期间,Print_Value()
打印出一个数字序列而不会遗漏任何值(数字的顺序不是问题)。
使用 C++11
中讨论的原子变量对这里有帮助吗?
class foo
{
public:
static int ID;
void Increase_value()
{
ID++;
Print_Value (ID-1);
}
void Print_Value(int k)
{
cout << k ;
}
};
最佳答案
Could using atomic variables discussed in C++11 help here?
当然。我会说让代码线程安全的最简单方法是制作 ID
一个std::atomic<int>
:
#include <atomic>
class foo
{
public:
static std::atomic<int> ID ;
// ^^^^^^^^^^^^^^^^
void Increase_value()
{
int old = ID++;
Print_Value (old);
}
void Print_Value(int k)
{ cout << k ; }
}
关于c++ - 如何使这段代码线程安全?编号++;打印值(ID);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16967398/