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.
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, ¶m1);
pthread_create( &thread2, NULL, thread, ¶m2);
while(1)
{
printf(".");
fflush(stdout);
sleep(mls);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("THE END\n");
return 0;
}
After having thought over the problem, I come to the conclusion that if the main use case is to really be sure both threads (thread "Hello" and thread "World") are gone there is no other way then to use pthread_join() on both.
As pthread_join() blocks the calling thread the natural conclusion is to start a third thread (thread "Dots") to draw the dots as requested.
This third thread (thread "Dots") then is signaled by the main()-thread waiting for the other two threads (thread "Hello" and thread "World") to finish after it returned from the two blocking call to pthread_join(). If this is done the third thread (thread "Dots") simply finishes. The latter could run detached, as no one is waiting for it to terminate.
while(pthread_kill(thread1, 0) == 0 && pthread_kill(thread2, 0) == 0)
{
printf(".");
fflush(stdout);
sleep(mls);
}
int pthread_kill(pthread_t thread, int sig);
You can use this function to retrieve status of the thread, if sig argument is 0, then no signal is sent, but error checking is still performed(eg. you can use this to check is thread 'alive').
It can return either 0 or error code(ESRCH - No thread with the ID thread could be found, and one more which is not important for this case), if returned value is 0 than thread is 'alive', if returned value is error code(ESRCH) than specified thread can't be found eg. it's 'dead'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With