C ++.

I have a problem with the following code:

#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; } 

[LATER EDIT] So, it looks like boost :: this_thread :: sleep is acquiring mutexes in screensavers, so I think I will stick to a simple old dream (), which for me is just old. [/ LATER EDIT]

From main (), I give out thread t1, which is 2 seconds, and another thread that does the following: fork () inside it, the parent waits for the child, and the child creates another thread, which also takes 2 seconds.

The problem is that if I use boost :: this_thread: to sleep, the program freezes or blocks in some way. If I use sleep (), then it works fine. Am I something wrong here? What is the difference between the two?

From the sleep man page, I get the following:

"sleep () causes the calling thread to fail until seconds elapse or a signal arrives that is not ignored."

Also from boost docs, boost: this_thread :: sleep seems to do the same.

+6
source share
1 answer

Here you do dangerous things: fork duplicates the entire program, but only one thread (current) in the new process works. So, all the mutex is here, but only one thread. And if some thread lock mutexes and your thread try to lock it in a new process, it will wait forever.

Here

 boost::this_thread::sleep(boost::posix_time::millisec(1000)); 

If you look at the boost include file, the dream looks like this:

 this_thread::sleep(get_system_time()+rel_time); 

get_system_time call tz_convert from libc that accept the mutex. And it seems that before you deploy another thread, block it and ...

+4
source

Source: https://habr.com/ru/post/901504/


All Articles