C++ Boost线程睡眠死锁

Flo*_*inP 6 c++ linux multithreading boost fork

我有以下代码的问题:

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void f1(uint count)
{
  while(count-- > 0)
  {
//    boost::this_thread::sleep(boost::posix_time::millisec(1000));
    sleep(1);
  }
}

void folkflore()
{
  int res = fork();
  //parent
  if ( res )
   {
     wait(NULL);
   }
  else
   {
     unsigned int x = 2;
     boost::thread tx(boost::bind(f1, 2));
     tx.join();
     _exit(-5);
   }
}

int main()
{
   std::cout << "Main program " << getpid() << std::endl;
   unsigned int x = 2;
   boost::thread t1(boost::bind(f1, 2));

   boost::thread m(folkflore);
   m.join();
   t1.join();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

[LATER EDIT]好的,所以看起来像boost :: this_thread :: sleep在幕后获得了一个互斥锁,所以我想我会坚持使用普通的老睡眠(),这对我来说是很好的.[/ LATER EDIT]

从main()我发出一个计算2秒的t1线程和另一个执行以下操作的线程:fork()在其中,父级等待子级,子级创建另一个也计数2秒的线程.

问题是如果我使用boost :: this_thread:sleep程序挂起或以某种方式死锁.如果我使用sleep(),那么它可以正常工作.我在这里做错了吗?这两者有什么区别?

从睡眠的男人页面我得到了:

"sleep()使调用线程休眠,直到秒数已经过去或信号到达,但不会被忽略."

同样来自boost docs,boost :: this_thread :: sleep似乎做同样的事情.

fgh*_*ghj 4

你在这里做了危险的事情:fork 调用复制了整个程序,但只有一个线程(当前线程)在新进程中运行。所以这里所有的互斥锁,但只有一个线程。如果某些线程锁定互斥体并且您的线程尝试将其锁定在新进程中,它将永远等待。

这里

boost::this_thread::sleep(boost::posix_time::millisec(1000));
Run Code Online (Sandbox Code Playgroud)

如果查看 boost 的包含文件,sleep 看起来像:

this_thread::sleep(get_system_time()+rel_time);
Run Code Online (Sandbox Code Playgroud)

get_system_time 从 libc 调用 tz_convert,它采用互斥体。看起来像在 fork 另一个线程之前锁定它,并且......