// 在以下簡單的程序中,運行結果應該是20000000,然而在GCC編譯運行后輸出的數介于一千萬到兩千萬之間,而且每次運行的結果都不同,這是為什么呢(┬_┬)#include <iostream>#include <thread>int count=0;void test(){for(int i=0;i<10000000;i++)count++;}int main(){thread t1(test), t2(test);t1.join();t2.join();std::cout<<count<<std::endl;return 0;}
2 回答

嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
線程對象在聲明之后就會立即執行。
thread t1(test), t2(test); //這里兩個線程同時啟動了,而你的線程函數沒加鎖 |
方法一:
//主函數應該這樣寫 int main() { thread t1(test); t1.join(); thread t2(test); t2.join(); std::cout<<count<<std::endl; return 0; } |
方法二:
//給線程函數加上鎖 #include <iostream> #include <thread> #include <mutex> using namespace std; int count=0; mutex gMutex; void test() { lock_guard<mutex> lk (gMutex); for ( int i=0;i<10000000;i++) count++; } int main() { thread t1(test), t2(test); t1.join(); t2.join(); std::cout<<count<<std::endl; return 0; } |
- 2 回答
- 0 關注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消