# C++ std::thread finish implementation

## Recommended Posts

Guess i have a thread and im on main thread of app now i would like to wait until thread finishes to execute.

void ProcessServerFrame()
{

Do stuff

}

And then from main thread i would like to check whenever thread finished to work

void CreateDWMTCPServer()
{
if (server != 0)
{
delete server;
server = 0;
}

}

Now i am not sure if thread is allowed to read data when other is writing to it or maybe theres some kind of queue that prevents that from happening, basically i dont want to check for server_thread_free when thread marks it as true

any thoughts?

##### Share on other sites

There are a number of threading primitives that may be necessary here, but I'm not 100% sure what you are trying to accomplish.

To safely read a variable that is written to from another thread, you might consider using std::atomic (in this case, likely std::atomic_bool). Atomics ensure that writes will occur fully before reads see the changes, avoiding reading a partially-modified value.

If you are actually waiting for the worker thread to be entirely finished (i.e. reach the end of its main function), then you could call join() on it from the main thread. Join will block the main thread until the worker thread exits.

If instead this is a worker thread that works on many small tasks, and you want to wait for it to be finished with the current task, then you likely want std::condition_variable. Conditional variables let you block one thread until the other signals it, which would allow your thread to sleep until the other thread wakes it up.

##### Share on other sites

In the worker example; what I use to utilize is a double sleeved Semaphore that first locks and then awaits itself if std::condition_variable is not an option. Then another thread may come and release the Semaphore so you have the same effect at the end. I first used to go with Mutex but it showed that on Windows platform a mutex is protected against self locking

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

1. 1
2. 2
3. 3
JoeJ
12
4. 4
5. 5
frob
11

• 12
• 16
• 13
• 20
• 12
• ### Forum Statistics

• Total Topics
632176
• Total Posts
3004593

×