【发布时间】:2015-06-26 17:08:31
【问题描述】:
如何在多线程上同步“for”循环计数器?
如果这些多线程程序
void Func(int n){
for(int i=0; i<n; i++){ //at the same time with other Func()
cout << i <<endl;
}
}
void main(){
std::thread t1(Func(2));
std::thread t2(Func(2));
t1.join();
t2.join();
}
在并行执行 Func() 时,我想同步“for”循环计数器“i”。
例如,程序有可能输出结果
0
1
0
1
但我想总是得到结果
0
0
1
1
可以吗?
【问题讨论】:
-
您的程序也可以打印其他内容(例如
00)。你希望计数器如何同步?您是否要始终保证按顺序打印日志消息?如果是这样,你为什么想要多个线程? -
这是提问的简化程序。我的原始程序是模拟多代理系统(分布式随机算法)。在原始程序中,我想同步所有代理的试验次数。
标签: c++ multithreading mutex sync critical-section