Avatar of bsdex
bsdex

asked on 

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

#include<iostream.h>
#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;
         exit(-1);
      }

 return threads;

}

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

Open in new window


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
Programming Theory

Avatar of undefined
Last Comment
bsdex
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

What you have is called a spin lock.
What you want would be mutex with condition variables.
Here is a good explanation of how they work in your context (from the pthread library)
https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of bsdex
bsdex

ASKER

Thank you very much :)
Programming Theory
Programming Theory

Programming theory deals with the design, implementation, analysis, characterization, and classification of programming languages and their individual features, along with introductory programming concepts like program structure, variable declaration and conditional and looping constructs. Sub-disciplines include the formal semantics of programming languages, type theory, program analysis and transformation, comparative programming language analysis, metaprogramming, domain-specific languages, compiler construction and run-time systems.

4K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo