I have this little program that is supposed to create a thread and cancel it.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *thread_function(void *arg)
{
while(1)
{
printf("hello \n");
//sleep(1);
}
return NULL;
}
int main()
{
pthread_t thread;
if(pthread_create(&thread, NULL, thread_function, NULL) != 0)
{
perror("Failed to create a thread");
return -1;
}
printf("After sleep in main thread\n");
if (pthread_cancel(thread) != 0) {
perror("Failed to cancel thread");
return EXIT_FAILURE;
}
pthread_join(thread, NULL);
printf("Thread is cancelled\n");
}
If I use sleep() in thread function, created thread is canceled almost immediately, but if I use printf(), it takes some time to cancel it. In man pthreads I read that sleep() is a safe cancel point while printf() may be a safe cancel point.
How does it work? I mean in what period of time that programme works printf() turns into a cancel point and my thread is being canceled?
And also if I run the programm (also using printf() in thread function) with time command, it can show that programm worked for 2 sec but in reality it worked longer. why?
PS: sorry for the mistakes, English is not my first language.
You need to sign in to view this answers