刚开始使用 C++11 线程库进行多线程(以及一般的多线程),并编写了一小段代码。
#include <iostream>
#include <thread>
int x = 5; //variable to be effected by race
//This function will be called from a thread
void call_from_thread1() {
for (int i = 0; i < 5; i++) {
x++;
std::cout << "In Thread 1 :" << x << std::endl;
}
}
int main() {
//Launch a thread
std::thread t1(call_from_thread1);
for (int j = 0; j < 5; j++) {
x--;
std::cout << "In Thread 0 :" << x << std::endl;
}
//Join the thread with the main thread
t1.join();
std::cout << x << std::endl;
return 0;
}
由于两个线程之间的竞争,我每次(或几乎每次)运行这个程序时都希望得到不同的结果。但是,输出总是:0
,即两个线程运行时就好像它们按顺序运行一样。为什么我得到相同的结果,是否有任何方法可以模拟或强制两个线程之间的竞争?
最佳答案
您的样本量相当小,并且在连续 stdout 刷新时有些 self 停顿。简而言之,您需要一把更大的锤子。
如果您想查看实际的竞争条件,请考虑以下内容。我特意添加了一个原子和非原子计数器,将两者都发送到样本的线程。部分试运行结果贴在代码后:
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
void racer(std::atomic_int& cnt, int& val)
{
for (int i=0;i<1000000; ++i)
{
++val;
++cnt;
}
}
int main(int argc, char *argv[])
{
unsigned int N = std::thread::hardware_concurrency();
std::atomic_int cnt = ATOMIC_VAR_INIT(0);
int val = 0;
std::vector<std::thread> thrds;
std::generate_n(std::back_inserter(thrds), N,
[&cnt,&val](){ return std::thread(racer, std::ref(cnt), std::ref(val));});
std::for_each(thrds.begin(), thrds.end(),
[](std::thread& thrd){ thrd.join();});
std::cout << "cnt = " << cnt << std::endl;
std::cout << "val = " << val << std::endl;
return 0;
}
上面代码的一些示例运行:
cnt = 4000000
val = 1871016
cnt = 4000000
val = 1914659
cnt = 4000000
val = 2197354
请注意,原子计数器是准确的(我在具有超线程的双核 i7 macbook air 笔记本电脑上运行,因此有 4 个线程,因此有 400 万)。对于非原子计数器则不能这样说。
关于c++ - 使用 C++11 线程强制线程之间的竞争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286304/