Hello,
I have an event handler in the main thread, which receive events from outside process. And upon the receipt of a new event, a new thread is created to handle the event. The problem is whenever I create a new thread inside the event handler, it will be destroyed when the event handler finishes. To solve this problem, after the creation of the thread, I am calling its join function, but this will cause the main thread which has the event handler to block its execution until the thread finishes its job. And actually this will be converted back to a single thread case. Where for each event, a new thread is created when the previous, thread is destroyed.
For more explanation ,please check the code below:
void ho_commit_indication_handler(message &msg, const boost::system::error_code &ec)
{
.....
}
void event_handler(message &msg, const boost::system::error_code &ec)
{
if (ec)
{
log_(0, __FUNCTION__, " error: ", ec.message());
return;
}
switch (msg.mid())
{
case n2n_ho_commit:
{
boost::thread thrd(&ho_commit_indication_handler, boost::ref(msg), boost::ref(ec));
thrd.join();
}
break
}
};
So my question is, how to handle each event through a separate thread and keep the thread alive even if the main thread exits the event_handler?
Note: I am using Boost 1.49 library
If what you're saying is correct. So why this happens in the following example:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono>
void foo()
{
std::chrono::milliseconds dura( 2000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited for 2Sec\n";
}
void bar(int x)
{
std::chrono::milliseconds dura( 4000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited for 4Sec\n";
}
int main()
{
std::thread first (foo);
std::thread second (bar,0);
return 0;
}
You're saying the thread is alive. I get the following output:
terminate called without an active exception
Aborted (core dumped)
This happened because the main thread has terminated, before the thread terminations
Thanks a lot.