user2138149
user2138149

Reputation: 17416

What happens to a thread in a vector when function execution ends?

I want to know more about std::thread, and specifically what will happen if I have a vector of threads, and one of the threads finishes executing.

Picture this example:

A vector of threads is created, which all execute the following function:

function_test(char* flag)
{
    while(*flag == 1) { // Do Something
    }
}

'char* flag' points to a flag signalling the function to stop execution.

Say, for example, the vector contains 10 threads, which are all executing. Then the flag is set to zero for thread number 3. (The 4th thread in the vector, as vector starts from zero.)

Good practice is to then join the thread.

vector_of_threads[3].join();

How many std::threads will the vector now contain? Can I re-start the finished thread with the same function again, or even a different function?

The reason for my question is that I have a vector of threads, and sometimes they will be required to stop executing, and then execution "falls off the end" of the function.

One solution to restart that thread would (I assume, perhaps incorrectly?) be to erase that element from the vector and then insert a new thread, which will then begin executing. Is this correct though, since when a thread stops, will it still be inside the vector? I assume it would be?

Edit

'function_test' is not allowed to modify any other functions flags. The flags are modified by their own function and the calling function. (For the purposes of this, imagine flag enables communication between main and the thread.)

Does this fix the data-race problem, or is it still an issue?

Upvotes: 1

Views: 1592

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171471

It's not specifically what you're asking about, but flag should be atomic<char>* or you have a data race, i.e. undefined behaviour. Also, if it only holds true or false I'd use atomic<bool>* and just test if (*flag).

As for your actual question:

How many std::threads will the vector now contain?

It will contains exactly the same number as it did previously, but one of them is no longer "joinable" because it doesn't represent a running thread. When the thread stops running it doesn't magically alter the vector to remove an element, it doesn't even know the vector exists! The only change visible in the main thread is that calling vector_of_threads[3].join() will not block and will return immediately, because the thread has already finished so you don't have to wait to join it.

You could erase the joined std::thread from the vector and insert a new one, but another alternative is to assign another std::thread to it that represents a new thread of execution:

vector_of_threads[3] = std::thread(f, &flags[3]);

Now vector_of_threads[3] represents a running thread and is "joinable" again.

Upvotes: 4

Related Questions