首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >std::condition_variable线程争用

std::condition_variable线程争用
EN

Stack Overflow用户
提问于 2014-06-25 06:43:57
回答 1查看 268关注 0票数 0

我有一个问题,我的condition_variables似乎不能互相通知。也就是说,我下面的代码在等待和通知线程中都使用了互斥锁,但仍然不能正确运行。

我是不是漏掉了什么?

谢谢。

代码语言:javascript
运行
复制
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

std::condition_variable cv_one;
std::condition_variable cv_two;

std::mutex m_one;
std::mutex m_two;

void one(  )
{
  std::unique_lock< std::mutex > lock { m_one };
  cv_one.notify_one( );

  std::cout << "one" << std::endl;
}

void two(  )
{
  {
    std::unique_lock< std::mutex > lock { m_one };
    cv_one.wait( lock );

    std::cout << "two" << std::endl;
  }

  {
    std::unique_lock< std::mutex > lock { m_two };
    cv_two.notify_one(  );
  }
}

void three( )
{
  std::unique_lock< std::mutex > lock { m_two };
  cv_two.wait( lock );

  std::cout << "three" << std::endl;
}

int main( int argc, char **argv )
{
  std::thread thread_one( one );
  std::thread thread_two( two );
  std::thread thread_three( three );

  std::cin.get(  );

  cv_one.notify_all( );

  thread_three.join( );
  thread_two.join( );
  thread_one.join( );

  return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2014-06-25 12:40:27

条件变量不会相互通知,因为您在错误的时间通知。例如,如果onetwo调用cv_one.wait(lock)之前调用cv_one.notify(),那么two将永远阻塞。就two而言,在它等待的时候没有线程通知它。这就是@v.oddou的意思,通知标志不会被存储。

std::cin行起到了延迟的作用,这就是为什么这里的输出是正确的。所有的线程都会到达它们等待条件变量的地方,在你按下按钮的延迟时间内。

您可以在此代码示例中看到问题的发生,它显示了线程在被唤醒时开始等待的时间。我切换到单个字符,这样输出就不会乱七八糟。

代码语言:javascript
运行
复制
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

std::condition_variable cv_one;
std::condition_variable cv_two;

std::mutex m_one;
std::mutex m_two;

void one()
{
    std::unique_lock< std::mutex > lock { m_one };
    std::cout << "x" << std::endl;
    cv_one.notify_one();

    std::cout << "a" << std::endl;
}

void two()
{
    {
        std::unique_lock< std::mutex > lock { m_one };
        std::cout << "y" << std::endl;
        cv_one.wait( lock );

        std::cout << "b" << std::endl;
    }

    {
        std::unique_lock< std::mutex > lock { m_two };
        cv_two.notify_one();
    }
}

void three()
{
    std::unique_lock< std::mutex > lock { m_two };
    std::cout << "z" << std::endl;
    cv_two.wait( lock );

    std::cout << "c" << std::endl;
}

int main( int argc, char **argv )
{
    std::thread thread_one(one);
    std::thread thread_two(two);
    std::thread thread_three(three);

    std::cout << "d" << std::endl;
    cv_one.notify_all();

    thread_three.join();
    thread_two.join();
    thread_one.join();

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24397545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档