Drgabble Drgabble - 1 year ago 59
C++ Question

How do I start a C++ thread at program startup?

I'm writing a C++ library to allow programs to talk to a service in the cloud. I want to run a background thread which periodically checks the server and restarts it in case of failure. However it would be nice for the main program outside the library not to have to worry about starting the thread. The use of library should be limited to

. By this point the thread should already be running.

How do I start a thread without the main program having to call any functions? Is there a way to do this in a static constructor of my service class so that it starts the thread at program start (as I would do in Java)?

Answer Source

You can do it precisely that way -- you can have a global object whose constructor starts the thread at program start.

Personally, I think having a library start up a thread unexpectedly is not a good idea, but it's possible that it makes sense in your use case. Make sure to document the thread's precise requirements, how to shut it down, and so on. All the threads in a process must cooperate.

Example code:

#include <cstdio>

//--------- BEGIN LIBRARY
class MyThread
{ // The real code goes here
    { printf("A MyThread has been constructed\n"); }
    { printf("A MyThread has been destroyed\n"); }
    void Start()
    { printf("A MyThread has been started\n"); }
    void Stop()
    { printf("A MyThread has been stopped\n"); }

class MyThreadCreator
{ // Just a helper class to construct/start/stop/destroy the other
    MyThread thread;
    MyThreadCreator() { thread.Start(); }
    ~MyThreadCreator() { thread.Stop(); }
MyThreadCreator p;
//---------- END LIBRARY

int main()
    return 0;

A MyThread has been constructed
A MyThread has been started
A MyThread has been stopped
A MyThread has been destroyed