如何在多线程中同步"for"循环计数器?
How to sync "for" loop counter in multithread?
如何在多线程上同步"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
我可以吗?
如果使用OpenMP线程化循环,则可以使用#pragma omp barrier
语句。
在C++11中,您可以使用condition_variable来阻塞所有线程,直到它们到达同一位置。
实现这一点的一种方法是为线程使用一些变量来协调事情(在下面,它们是全局变量,只是为了简单起见)。
mutex m;
condition_variable c;
static int index = 0;
static int count = 2;
index
变量表示线程在哪个索引处,count
变量表示仍有多少线程在索引处。
现在你的循环变成:
void Func(int n){
for(int i=0; i<n; i++){ //at the same time with other Func()
unique_lock<mutex> l(m);
c.wait(l, [i](){return index == i;});
cout << i <<endl;
if(--count == 0)
{
++index;
count = 2;
c.notify_one();
}
}
}
这是完整的代码:
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
mutex m;
condition_variable c;
static int index = 0;
static int count = 2;
void Func(int n){
for(int i=0; i<n; i++){ //at the same time with other Func()
unique_lock<mutex> l(m);
c.wait(l, [i](){return index == i;});
cout << i <<endl;
if(--count == 0)
{
++index;
count = 2;
c.notify_one();
}
}
}
int main(){
std::thread t1(Func, 20);
std::thread t2(Func, 20);
t1.join();
t2.join();
}
您可以使用std:atomic
变量并将其传递给所有线程。
void Func(int n, int & i){
for (; i<n; i++){ //at the same time with other Func()
cout << i << endl;
}
}
void main(){
std::atomic<int> counter = 0;
std::thread t1(Func, 2, std::ref(counter));
std::thread t2(Func, 2, std::ref(counter));
t1.join();
t2.join();
}
此外,您应该注意,您在示例中对线程进行装箱的方式是不正确的。其次,如果在多个线程中使用cout
,则每个cout
都应该用std::mutex
保护,因为cout
不是线程安全的。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式