Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::thread join function blocks calling thread

Question 1: I read that when you call join after creating a thread it blocks the thread that called it until the thread function returned. I'm trying to build a multiply client server which can accept clients and create thread for each one. The problem is that after the first client joins and created it's thread and called join the listen thread hangs until it is done. What can I do to make this thread run without blocking the calling thread? (In C# I would just call Start() and the calling thread kept run as usual).

Question 2: In general (Im probably missing something), why would someone want a blocking thread? What's the point of that? Wouldn't it be easier and faster to just call a regular function?

If someone could of explain me how to achieve the same thing like the threads in C# it would be great!

Thanks in Advance! Sorry for my bad english.

like image 878
UnTraDe Avatar asked Mar 24 '23 00:03

UnTraDe


1 Answers

What can I do to make this thread run without blocking the calling thread

You can create the thread and then invoke detach() on it, so that the destructor of the thread object won't throw an exception if the thread has not terminated yet. I would honestly advise to think twice before adopting this kind of fire-and-forget design. In C++11, you may want to call std::async instead (and in that case you may want to take a look at this Q&A, where a workaround is proposed for a current drawback of that function).

In general (Im probably missing something), why would someone want a blocking thread? What's the point of that? Wouldn't it be easier and faster to just call a regular function?

Well, if your program has absolutely nothing else to do than waiting for the task to be completed, then yes - I would say, just use a synchronous call. But it might be the case that your program wants to do something in parallel, and once it is done it may need to wait for the end of the asynchronous computation in order to continue. In that case, it would need to join with the thread.

like image 187
Andy Prowl Avatar answered Apr 10 '23 20:04

Andy Prowl