#include <thread>
#include <iostream>
struct A
{
void fun1() {
//不做任何事
}
void fun2() {
//不做任何事
}
};
void thread1(A *a)
{
while (true)
a->fun1();
}
void thread2(A *a)
{
while (true)
a->fun2();
}
int main()
{
A a;
std::thread t1(thread1, &a);
std::thread t2(thread2, &a);
t1.join();
t2.join();
}
在執行緒中對a->fun1(); a->fun2();的呼叫安不安全。(不考慮成員函式內的競爭)
uj5u.com熱心網友回復:
非常安全 ,因為join等待執行結束uj5u.com熱心網友回復:
你在A類加個成員變數試試?uj5u.com熱心網友回復:
如果fun1和fun2里面使用同一個變數就不安全,會發生競態,如果沒有此關系,算是勉強可用,應該你沒有上鎖,舉個例子,加入你在fun1里面輸出hello world,fun2里面輸出 123,很可能輸出的是hello 123轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/8116.html
標籤:C++ 語言
下一篇:C++中出現的問題
