为什么这个条件变量不起作用
Why this conditon variable is not working?
我试图理解C++标准中可用的condition_variable
。所以在我写的下面的测试代码中,我希望在主线程中打印 50 个数字后唤醒func1
,但这里它只打印主线程中的所有数字?
您能否在这里帮助我更好地理解condition_variable
更好地指示要唤醒的某个线程
我试图使用以下代码来理解条件变量:
#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex mu;
std::condition_variable multiple;
bool isLoaded = false;
void func1()
{
std::unique_lock<std::mutex> unLock(mu);
multiple.wait(unLock, []() {return isLoaded; });
for (int i = 0; i < 100; i++)
{
cout << "This is from thread; " << i << endl;
}
}
int main()
{
std::thread t1(func1);
std::lock_guard<std::mutex> gaurd(mu);
cout << std::thread::hardware_concurrency()<< endl;
for (int i = 0; i < 100; i++)
{
if (i == 50)
{
isLoaded = true;
multiple.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(4));
}
cout << "This is from main; " << i << endl;
}
t1.join();
getchar();
return 0;
}
您永远不会在主线程中释放mu
。尝试这样的事情:
int main()
{
std::thread t1(func1);
cout << std::thread::hardware_concurrency()<< endl;
for (int i = 0; i < 100; i++)
{
if (i == 50)
{
{
std::lock_guard<std::mutex> gaurd(mu);
isLoaded = true;
}
multiple.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(4));
}
cout << "This is from main; " << i << endl;
}
t1.join();
getchar();
return 0;
}
一般来说,您需要在绝对最短的时间内保持锁。
你在程序开始时采用互斥锁mu
并且永远不会放手,所以这个互斥锁下的任何其他代码都不会被执行。
相反,您应该仅在更改共享变量时保留它,例如:
{
std::lock_guard<std::mutex> gaurd(mu);
isLoaded = true;
multiple.notify_one();
}
相关文章:
- 通过 get-Method 访问变量在类外不起作用
- 键盘不起作用 - Arduino Uno - 与变量有关的多个错误
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 指针变量在 cout 函数中不起作用
- C++结构模板变量快捷方式定义不起作用
- C++ 互斥锁可以交叉方法/变量吗?如果是这样,为什么在这里不起作用?
- 变量和常数的C++划分不起作用
- C++ Eclipse:二叉搜索树节点>数据=变量似乎不起作用
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 为什么这个条件变量不起作用
- 在循环中更改数组的变量不起作用
- 添加到私人变量不起作用
- 全球变量不起作用Raspberry Pi
- 为什么我的加权_grade变量不起作用
- 调用函数从类返回私有变量不起作用
- 递增引用变量不起作用
- 为什么作用域解析对覆盖的变量不起作用?
- Boost::scoped_lock对局部静态变量不起作用
- 为什么<int>常量引用返回的向量变量不起作用
- OpenGL 3.3 着色器统一变量不起作用