【问题标题】:many to one conditional thread lock多对一条件线程锁
【发布时间】:2013-09-23 14:28:59
【问题描述】:

问题: 首先,这是我的问题的一个简化示例,它实际上是已经由其他人编写的大型框架的一部分,我必须在其中调整我的代码。

我有 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 一直运行,除非被阻塞,而且我只想在其他函数之一运行一次时运行该函数。就像我之前说的,我不能自己调用​​function3,我只能操作函数中的代码。

最好的方法是什么?

经过激烈的谷歌搜索后,我只提出了条件变量、信号量和互斥锁,但我对它们了解得不够多,不知道如何正确实现它。

非常感谢任何帮助/输入/提示。

【问题讨论】:

  • 您不太确定的一件事是function3() 中的处理程序代码是否应该与function1()function2() 的调用次数相匹配。 IE。如果function1() 被调用两次和function2() 被调用三次,那么function3() 中的迭代循环是否应该准确地 触发五个事件并解除?
  • 很抱歉。实际上,这两个函数总是会同时被调用,但并不总是确定它们都会被调用,有时只会调用其中一个。但是当两者都被调用时,它是同时调用的。在这两种情况下,我只希望 function3 运行一次。就像 OR 一样,如果其中一个运行,则运行 function3,如果两者都运行,则仍然运行 function3 一次。
  • 编辑到上面那个。实际上唤醒function3的函数中会有16个。这些函数总是会同时被调用,但并不总是确定所有函数都会被调用,有时可能是一半,有时只是一个。在所有情况下,我只希望 function3 运行一次。就像 OR 一样,如果其中一个运行,则运行 function3,如果同时运行多个,则仍然只运行一次 function3。

标签: c++ multithreading mutex semaphore condition-variable


【解决方案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,直到调用其他两个之一。所以这是一种行为的改变,它增加了额外的锁竞争。

【讨论】:

  • 这段代码我还没有测试过,但是如果同时调用这两个函数会怎样呢?如果 cond-var 已经被通知,通知是否会出错?如果这是一个愚蠢的问题,请原谅。
  • @trudesagen:不,您可以根据需要随时通知情况。如果没有人在等待它,则通知将丢失。因此布尔标志。
  • 我明天将对此进行全面测试,似乎有一些我需要先修复的缺失库。感谢您的意见。
  • 您好,很抱歉回复晚了。这对我来说似乎工作正常,谢谢。
猜你喜欢
  • 2015-11-04
  • 2013-02-03
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多