【问题标题】:The execution sequence after conditional variable notify条件变量 notify 后的执行顺序
【发布时间】:2016-11-10 14:14:34
【问题描述】:

有两个线程(称为 T1 和 T2)通过 boost 条件变量和互斥锁相互同步,例如:

boost::condition_variable global_cond;
boost::mutex global_mutex;
boost::unique_lock<boost::mutex> lock( global_mutex);

thread1() {
  global_cond.notify_one();
  code_block_a();
}

tread2() {
  global_cond.wait(lock)
  code_block_b();
}

假设我可以保证 thread2 先来等待,然后 thread1 会做通知。

我的问题是,code_block_a() 或 code_block_b() 将首先执行是否具有确定性?

【问题讨论】:

  • 一般?不,在你的代码中?谁知道。也许如果你发布了它。

标签: c++ multithreading boost-mutex


【解决方案1】:

不保证。系统可以在thread1 调用notify_one() 之后立即执行上下文切换并允许thread2() 运行。也可能不会。

请注意,您的代码通常有问题,因为 global_cond.wait(lock) 可能会被虚假唤醒,tread2 甚至可以在 thread1() 运行之前运行 code_block_b()

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2016-02-22
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多