刚刚开始使用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 冲洗中有些自停。简而言之,你需要一个更大的锤子。
如果要查看实际争用条件的实际运行情况,请考虑以下事项。我特意添加了一个原子和非原子计数器,将两者发送到示例的线程。一些测试运行结果发布在代码之后:
#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 万(。对于非原子计数器来说,情况并非如此。
启动第二个线程会产生大量的启动开销,因此它的执行几乎总是在第一个线程完成 for 循环后开始,相比之下,这几乎不需要时间。若要查看争用条件,需要运行耗时更长的计算,或者包括 I/O 或其他需要大量时间的操作,以便两个计算的执行实际上重叠。