问题: 首先,这是我的问题的一个简化示例,它实际上是已经由其他人编写的大型框架的一部分,我必须在其中调整我的代码。
我有 3 个函数。其中两个函数(function1 和 function2)被程序的其他部分异步和同步调用。 我的最后一个函数 (function3) 连续运行,就像一个 while 循环,它唯一做的就是在每次代码迭代时触发一个事件代码。 我只希望这最后一个函数在其他两个函数之一完成迭代/被调用时运行。 我无法更改它们的调用方式/时间,我只能阻止代码的执行并取消阻止。
我是 C++ 的新手,我曾尝试使用互斥体解决这个问题,但我没有运气。 我可以添加代码,但它真的就像我解释的那样。
void function1(){ // this function is called by other parts of the program
//some code
}
void funtion2(){ //this function is also called by other parts of the program
//some other code
}
void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
fireEvent();//fires an event to run some other code
}
因此,函数 3 一直运行,除非被阻止,我只想在其他函数之一运行一次时运行该函数。就像我之前说的,我不能自己调用 function3,我只能操作函数中的代码。
解决这个问题的最佳方法是什么?
经过大量谷歌搜索后,我只提出了条件变量、信号量和互斥锁,但我对它们的了解还不够多,无法知道如何正确实现它。
非常感谢任何帮助/输入/提示。
最佳答案
一个简单的方法是这样的:
mutex g_mutex;
condition_variable g_cond;
bool flag = false;
void function1(){ // this function is called by other parts of the program
//some code
lock_guard<mutex> lock(g_mutex);
flag = true;
g_cond.notify_one();
}
void funtion2(){ //this function is also called by other parts of the program
//some other code
lock_guard<mutex> lock(g_mutex);
flag = true;
g_cond.notify_one();
}
void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
{
unique_lock<mutex> lock(g_mutex);
g_cond.wait(lock, []{return flag;}); // wait here until func1 or func2 have been called
flag = false;
}
fireEvent();//fires an event to run some other code
}
int main() {
// your code goes here
return 0;
}
但是这会阻塞您的 function3
直到其他两个函数中的一个被调用。所以这是行为的改变,它增加了额外的锁争用。
关于c++ - 多对一条件线程锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18961907/