Mario
Mario

Reputation: 199

C++ Declare same thread variable multiple times (in a loop)

I was wondering what will happen if I do something like this:

void afunction(/*parameters*/) { /*do something*/ }

// And then in main... 

while(1) {
    thread aThread(afunction, /*parameters*/);
    athread.detatch();
    sleep(1);
}

Does this create an infinite amount of threads (until the system crashes)? Or does it overwrite the old thread after 1 second (like killing the thread and create a new one)? Are there any problems I have to worry about?

Upvotes: 0

Views: 1363

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73041

The former.

In particular, when control enters the while-loop-body's scope, the thread object aThread is created and a new OS-thread is spawned by its constructor (note I'm assuming here that you are using std::thread and not some other thread class).

Then you call detach() on the thread-object, so the OS-thread is no longer associated with the aThread object, but it is still running.

Then after a one-second delay, the end of the scope is reached, so the aThread object is destroyed, but since the OS-thread was detached from the aThread object, the OS-thread is left to continue running on its own.

Then the scope is entered again for the next iteration of the while-loop, and the whole process repeats, indefinitely.

In general, it's better to call join() on your threads rather than detach(), since that will allow your program to do a well-ordered shutdown. Without join(), it's difficult or impossible to tear down process-wide resources safely, since you can't guarantee that the still-running threads might not be in the middle of using those resources at the time the tear-down occurs. Therefore, most well-written multi-threaded programs will call join() on all currently running threads, just before the end of main(), if not earlier.

Upvotes: 2

Related Questions