线程池的同步
Synchronizing of Threadpool
在每个时间步骤中,多个工作线程W[1..10]应该是空闲的,直到它们从主线程收到开始工作的信号。完成他们的每一项工作,向主线程发出完成的信号,并返回到以前的等待状态。主线程应该在等待,而workersreads正在做他们的工作。
我曾尝试使用std::condition_variable
和std::mutex
来完成此操作,但失败了。对于不使用boost或其他高级库的问题,正确的方法是什么出于性能原因,我希望避免在每一步中生成和连接线程非常感谢。
编辑:
const size_t thread_num = 10;
int busy_count = thread_num;
std::condition_variable cv;
std::mutex cv_m;
std::condition_variable cv_lock1;
std::mutex cv_m_lock1;
bool lock_1;
bool end_all = false;
void wthread()
{
do {
{
std::unique_lock<std::mutex> lk(cv_m_lock1);
cv_lock1.wait(lk, []{return lock_1 == false; });
}
if (end_all)
{
std::cout << "exitn";
return;
}
// do work
{
std::lock_guard<std::mutex> lk(cv_m);
busy_count--;
std::cout << busy_count << " ";
}
cv.notify_all();
{
std::unique_lock<std::mutex> lk(cv_m_lock1);
cv_lock1.wait(lk, []{return lock_1 == true; });
}
} while (true);
}
int _tmain(int argc, _TCHAR* argv[])
{
std::thread *t[thread_num];
lock_1 = true;
for (unsigned int i = 0; i < thread_num; i++)
t[i] = new std::thread(wthread);
for (int i = 0; i < 10; i++)
{
busy_count = 10;
lock_1 = false;
cv_lock1.notify_all();
{
std::unique_lock<std::mutex> lk(cv_m);
cv.wait(lk, []{return busy_count == 0; });
}
lock_1 = true;
cv_lock1.notify_all();
}
end_all = true;
lock_1 = false;
cv_lock1.notify_all();
for (unsigned int i = 0; i < thread_num; i++)
t[i]->join();
return 0;
}
类似的东西
std::thread thread1([](){/*do something*/});
std::thread thread2([](){/*do something*/});
std::thread thread3([](){/*do something*/});
thread1.join();
thread2.join();
thread3.join();
主线程将等待线程1..3完成工作;并且这些线程将同时工作
相关文章:
- 在C++中同步线程
- 将 10 个线程与原子布尔值同步
- 线程过程中的线程同步问题
- 如何定期同步线程?
- 同步线程安全的API,用于暴露缓存数据
- 如何在 pthreads 中正确同步线程
- 通过shared_ptr同步:线程清理器误报
- 如何同步线程以捕获相同数量的帧
- 同步线程和信号
- 使用条件变量(监视器)同步线程
- 同步线程创建和销毁(静态)对象
- NVIDA的CUDA"__syncthreads()"在传统C++中的等价物是什么。如何专业地同步线程?
- 使用事件同步线程
- 如何同步线程(消费者/生产者)
- 以最优雅的方式同步线程
- 使用互斥锁同步线程
- 计算着色器-如何全局同步线程
- GPU for loops:避免扭曲发散和隐式同步线程
- 如果已知访问顺序是安全的,如何在没有互斥锁的情况下同步线程/CPU
- Qt - 同步线程不起作用 - 线程停止但实际上不会停止,有时在不应该停止的时候停止