how to terminate infinite loop (threading)

Hi, I have question about exiting the while loop. I'm writing code in which I'm creating two threads, which prints strings and main() part has to print dots(".") every 500 miliseconds. Can you please help me how to exit the while loop after the second thread terminates, to get something like this on output:
...Hello...World....THE END

thank you for your help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main() 
{
	int mls = 0.5 ;	
	pthread_t thread1;
	pthread_t thread2;
	
	struktura param1 = { "Hello", 2};
	struktura param2 = { "World", 4};
	
	pthread_create( &thread1, NULL, thread, &param1);
	pthread_create( &thread2, NULL, thread, &param2);
	
	while(1)
	{
		printf(".");
		fflush(stdout);
		sleep(mls);	
	}
	
	pthread_join(thread1, NULL);
	pthread_join(thread2, NULL);
	
	printf("THE END\n");
	return 0;
}
Instead of 'sleep' you could try joining the threads with a timeout, and end the loop when the join succeeds (but continue if you reach the timeout, of course)
Last edited on
Using a static boolean value. Because boolean operators can be modified atomically there is no need to use any mutexes/locks etc
I highly recommend against that; code may detect the state of the boolean, the boolean may then change, and then the code will act on a false state.
Last edited on
@L B: That is always going to be the case with any flag used across threads. The only alternative is to lock the entire section of code that relies on that flag, but that often negates the benefit of threading.

If you're using a flag it's fine to have it change after you check it as long as the other thread changing it does not modify anything that would cause issues (e.g closing a file). But this comes back to designing the responsibilities of your threads appropriately.

a static boolean value


Using raw booleans and active waiting is wasting CPU cycles and asking for some other trouble and L B is right. The obvious alternative is using Hoare's monitor (signal / wait pair) or, if we allow threads to exit, just joining them as L B said.

The problem with only setting a boolean flag is the thread that sets it has no control over the state of the threads it wants to signal / break. It just continues. Which means it must not be allowed to reset this flag back ever.

BTW: The flag needs to be volatile, not only static. And static mutable data are code-smell.
Last edited on
Topic archived. No new replies allowed.