Search code examples
c++multithreadingboostboost-thread

Boost Thread - Create a Thread without join()


I have an application that creates a thread, and it will be listening for incoming connections. And the main thread will be doing other things.

boost::mutex mutex;
void
ThreadFunction(int port, int(*callbackFunc)(int, int))
{
    mutex.lock();
    std::cout << "Cannot get to this point" << std::endl;
    mutex.unlock();
    Application app;
    app.run(port, callbackFunc);
}

void 
Init(int port, int(*callbackFunc)(int, int))
{
    std::cout << callbackFunc(1,1) << std::endl;
    boost::thread t(boost::bind(&ThreadFunction, port, callbackFunc));
}

int
main(){
    int port = 2340;
    Init(port, *callbackfunction);
    return 0;
}

The problem I am having is that it never access the std::cout << "Cannot get to this point" << std::endl; However, if I call join() after I create the thread, it works just fine but then it is blocking the application.

What do I need to do for the thread call the ThreadFunction?


Solution

  • Your application terminates (by leaving main()) before the thread gets a chance to do its work. Once you implement a wait-for-connections loop, the problem will be resolved. So, no need to do anything.