CPP如何使主线程等到其他线程在周期中完成
cpp how to make main thread wait until other threads are finished in cycle
我正在尝试在不同线程的周期中运行一个CPP代码,并希望我的主线程等到所有其他线程完成。我这样做:
MyClass {
function(Obj1& res, Obj2& input);
}
AnotherClass {
MyClass class;
anotherFunction(int size) {
Obj1* resvec = new Obj1[size];
Obj2* inputvec = new Obj2[size];
doSmth1(resvec, inputvec);
thread* thpool = new thread[size];
for(int i = 0; i < size; ++i) {
thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
}
for(int i = 0; i < size; ++i) {
thpool[i].join();
}
doSmth2(resvec);
}
}
但是代码返回错误的答案,但是,如果我喜欢这个
MyClass {
function(Obj1& res, Obj2& input);
}
AnotherClass {
MyClass class;
anotherFunction(int size) {
Obj1* resvec = new Obj1[size];
Obj2* inputvec = new Obj2[size];
doSmth1(resvec, inputvec);
thread* thpool = new thread[size];
for(int i = 0; i < size; ++i) {
thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
thpool[i].join();
}
doSmth2(resvec);
}
}
代码返回正确的答案,但没有给出速度的优势。看来我在代码中做错了什么,有人可以帮我吗?谢谢!当我致电方案时会出现问题。
方案中实现的方法
当您连接时,主线程将等到线程结束,因此,如果您在循环中运行,则主线将等待每个线程完成。我认为您要做的是让所有线程脱落,但是当(i == size-1(让他加入时。
只需通过使用Sleep((函数来增加主线程的睡眠时间。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 查询时间/周期是针对所有内核/线程的序列化请求还是并行请求?
- CPP如何使主线程等到其他线程在周期中完成
- 如何使用固定的线程循环周期最小化CPU消耗
- 松弛的内存顺序效果是否可以扩展到执行线程的生命周期之后?
- 让线程每个周期调用init一次
- 管理派生类中的线程生命周期