c++ - boost 线程同步

标签 c++ multithreading boost

当我在 thread() 中注释行 wait(1) 时,我没有看到同步输出。我可以让它们同时运行(一个接一个)而不必使用“wait(1)”吗?

#include <boost/thread.hpp> 
#include <iostream> 

void wait(int seconds) 
{
  boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
}

boost::mutex mutex; 

void thread()
{
  for (int i = 0; i < 100; ++i) 
  {
    wait(1); 
    mutex.lock(); 
    std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 
    mutex.unlock(); 
  }
}

int main()
{
  boost::thread t1(thread); 
  boost::thread t2(thread);

  t1.join();
  t2.join();
}

最佳答案

“同时(一个接着一个)”是矛盾的。通过调用 sleep() 它们会同时运行。无需调用 sleep(),它们就会一个接一个地运行。只有 100 行要输出,线程 t1 在 t2 开始执行之前完成。在我的计算机上,在 t1 运行足够长的时间以使 t2 启动之前,我必须将循环计数器设置为 10000,而 t1 仍在执行:

Thread 0x2305010: 0
Thread 0x2305010: 1
Thread 0x2305010: 2
...
Thread 0x2305010: 8730
Thread 0x2305010: 8731
Thread 0x23052a0: 0
Thread 0x23052a0: 1
...
Thread 0x23052a0: 146
Thread 0x23052a0: 147
Thread 0x2305010: 8732
Thread 0x2305010: 8733
etc

哦,是的,如果您的目标是让两个线程轮流执行,boost::condition_variable 就是解决方案:

boost::mutex mutex;
boost::condition_variable cv;

void thread()
{
  for (int i = 0; i < 100; ++i)
  {
    boost::unique_lock<boost::mutex> lock(mutex);
    std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
    cv.notify_one();
    cv.wait(lock);
  }
  cv.notify_one();
}

关于c++ - boost 线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2892832/

相关文章:

c++ - 使用 Microsoft Visual Studio 8 在 boost 中编译 BJAM 1.33.1

c++ - 当c++模板定义带有=时是什么意思

c++ - 在另一个字符串中按字符复制字符串字符

c# - 在C#中手动设置线程退出代码?

c++ - 对更多 boost::intrusive 容器中的一个元素感到困惑

c++ - 为什么 Boost 库会返回 "convertible to ` bool `"rather than just returning ` bool`s?

c++ - 静态 constexpr 变量的自初始化,格式是否正确?

c++ - 为什么 BOOST_TEST((Iterator == Iterator)) 需要额外的括号?

python - 我应该总是使用 threading.Thread.join()

java - 如何从一个线程访问另一个线程的方法?