troubleshooting Question

Waiting in main thread for a flag to be set by thread

Avatar of bsdex
bsdex asked on
Programming Theory
3 Comments1 Solution506 ViewsLast Modified:
#include <cstdlib>
#include <pthread.h>
using namespace std;

bool flag = false;

void* doStuff(void t)
	//does lots of stuff
	flag = true;
	//does lots of stuff. takes long time to do that
pthread_t threadCall(int t)
   pthread_t threads;
   int rc;
   int i;
      rc = pthread_create(&threads, NULL, doStuff, (void *)t);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;

 return threads;


int main()
	int t =10;
	pthread_t thread= threadCall(t);
	//does some function calls
	//do some stuff when flag gets true.
	pthread_join(thread, NULL);
	return 0;

above is my code. I want to wait in main thread for flag to be set true by another thread as you can see here doStuff() function set the flag true.  In main thread, statement while(!flag); waits in busy waiting until flag get true.

Is there any other way to wait in main thread except this busy waiting.

Thanks in advance
Join our community to see this answer!
Unlock 1 Answer and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros