问题: 首先,这是我的问题的简化示例,它实际上是由其他人编写的大型框架的一部分,我必须在其中调整我的代码。
我有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
}
因此,function3一直运行,除非被阻止,并且我只想在每次其他一个函数都有一个run-through时运行该函数。就像我之前说过的,我不能自己调用function3,我只能操作函数中的代码。
解决这个问题的最佳方式是什么?
经过激烈的谷歌搜索后,我只提出了条件变量,信号量和互斥量,但我不太了解他们知道如何正确实现它。
非常感谢任何帮助/输入/提示。
答案 0 :(得分:1)
一种直截了当的方式是这样的:
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
,直到其他两个人被召唤。所以这是行为的改变,它增加了额外的锁争用。