【问题标题】:Preventation from starting a thread twice防止两次启动线程
【发布时间】:2011-09-21 12:49:05
【问题描述】:

假设你有一个小计算方法,它是由一个线程启动的:

boost::mutex mMutex;

void MyClass::DoSomething {
  boost::unique_lock<boost::mutex> tLock(mMutex);
  if(tLock.owns_lock() {
    // do some stuff...
  }
}

你想在一个线程中启动它,从不同的成员函数引发。它们可以被称为同时,但你不知道什么时候:

void MyClass::Process {
  boost::thread t1(&MyClass::DoSomething, this);
  // go on ...
}

void MyClass::Foo {
  boost::thread t2(&MyClass::DoSomething, this);
  // and something more ...
}

如果t1 正在运行,如何防止t2 被执行?我的unique_lock 似乎失败了。

【问题讨论】:

  • @Kerrek For t2 也可以获取锁

标签: c++ multithreading boost-thread


【解决方案1】:

基于 Naszta 的想法,这是一种使用原子布尔和原子交换的可能方法:

std::atomic<bool> thread_in_use(False);

void DoSomething()
{
  if (thread_in_use.exchange(true))
    return;

  // ...

  thread_in_use = false;
}

【讨论】:

    【解决方案2】:

    创建一个变量,然后在启动t1 线程之前,以原子方式增加该变量。完成后,以原子方式将该变量减小为 null。在Foo 中,您应该只检查此变量是否为空。

    Check this example.

    【讨论】:

    • 这可能是一个解决方案,但我试图找出一种不增加、减少和检查的方法。因为有时人们可能会忘记这样做:)
    • @Benjamin:它比互斥锁更有效,也应该锁定和解锁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2013-02-13
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多