C++ 多线程:条件变量
c++ multithreading: condition variable
我是多线程的新手。这就是我想要的
thread_function(){
// do job1;
//wait main thread to notify;
// do job2;
}
main(){
//create two threads
//wait both threads to finish job1
//finish job3, then let both threads start job2
//wait both threads to join
}
最好的方法是什么?谢谢。
这是我的代码
void job1(){
}
void job2(){
}
void job3(){
}
int main(){
thread t11(job1);
thread t12(job1);
t11.join();
t12.join();
job3();
thread t21(job2);
thread t22(job2);
t21.join();
t22.join();
}
我的问题是我是否可以将 job1 和 job2 组合到一个函数中,并使用条件变量来控制顺序?
我会给你一个示例(类似于生产者-消费者问题)这不是您正在寻找的确切解决方案,但下面的代码将指导您,
下面的 "q" 受互斥锁保护,条件变量等待它收到通知或 !q.empty(虚假唤醒需要)或超时。
std::condition_variable cond;
std::deque<int> q;
std::mutex mu;
void function_1() {
int count = 50;
while (count > 0)
{
// Condition variables when used lock should be unique_lock
// lock the resource
std::unique_lock<mutex> locker(mu);
// defer the lock until further
//std::unique_lock<mutex> locker(mu, std::defer_lock);
q.push_front(count);
locker.unlock();
//cond.notify_one();
cond.notify_all();
//std::this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void function_2(int x,int y) {
int data = 0;
while (data != 1)
{
// mu is the common mutex this resource is protected for the q.
std::unique_lock<mutex> locker(mu);
// this will only be done when !q.empty()
// This will make sure it is handled by multiple threads
auto now = std::chrono::system_clock::now();
if (cond.wait_until(locker, now + y * 100ms, []() { return !q.empty(); }))
{
auto nowx = std::chrono::system_clock::now();
cout << "Thread " << x << "waited for " << (nowx-now).count() << endl;
}
else
{
cout << "Timed out " << endl;
break;
}
data = q.back();
q.pop_back();
locker.unlock();
cout << x << " got value from t1 " << data << endl;
}
}
int main()
{
std::thread t1(function_1);
std::thread t2(function_2,1,50);
std::thread t3(function_2,2,60);
std::thread t4(function_2,3,100);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
相关文章:
- 基于模板值的条件变量
- 没有超时的C++条件变量
- 在条件变量中触发错误信号的频率是多少
- 使用不变量来确定二分搜索中的边界条件
- 在通知提升间处理条件变量时未按住锁会导致问题
- 通知条件变量后使用互斥锁
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 滥用条件变量
- 升压插值条件变量可以虚假唤醒吗?
- 根据模板类型有条件地删除变量
- 子线程中的条件变量等待停止主线程中的执行
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 条件变量基本示例
- 正在连接的等待条件变量的线程会发生什么情况?
- C++11如何在1个线程中使用条件变量处理2个线程安全队列
- 当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
- 为什么在同一条件变量上使用多个互斥锁会使此代码崩溃?
- 条件变量:wait_for.gcc错误
- 如何"stop"正在等待条件变量的分离线程?
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取