Jump to content
  • Advertisement

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.
  Thread Func
  void ProcessServerFrame()
	server_thread_free = false;
	while (!server_thread_finished)
      Do stuff
  	server_thread_free = true; 

And then from main thread i would like to check whenever thread finished to work
  void CreateDWMTCPServer()
	if (server != 0)
		server_thread_finished = true;
		while (!server_thread_free) {}
		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 this post

Link to post
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 this post

Link to post
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

Share this post

Link to post
Share on other sites

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

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!