Reputation: 11
I've tested the thread cancellation process, and have a code like this. It works on my ARM machine, and sometimes works fine, sometimes leads to a segfault, sometimes stuck after created.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
void *t(void *ptr)
{
printf("in t\n");
sleep(0.3);
return NULL;
}
int main() {
pthread_t p;
pthread_create(&p, NULL, t, NULL);
printf("created\n");
pthread_detach(p);
pthread_cancel(p);
printf("canceled\n");
return 0;
}
have no idea which part is leading to the issue(stuck/segfault).
Upvotes: 1
Views: 1270
Reputation: 2934
Make sure, that:
pthread_cancel(p);
is called before:
pthread_detach(p);
and you will be fine. More details, why this works, can be found in this answer: Is it safe to call pthread_cancel() on terminated thread?
Generally, a thread identifier must not be used anymore, after either pthread_join()
or pthread_detach()
has been called with it.
Upvotes: 0
Reputation: 182769
I answered this same question 18 years ago. It is not safe to call pthread_cancel
on a detached thread.
Your code has a race condition so its behavior is undefined. If the thread manages to terminate before you call pthread_cancel
, you are passing an invalid parameter to pthread_cancel
and that is undefined behavior.
If the code in main
is managing the lifetime of the thread, do not detach it because otherwise there is no way to ensure the thread ID remains valid. If the code in main
is not managing the lifetime of the thread, do not call pthread_cancel
in it. You will never find a safe way to split the difference.
You should think of pthread_detach
as rendering the thread ID invalid (or "semantically closed" as Glenn Burkhardt put it) and not use it again.
As Some programmer dude points out, your sleep
rounds to zero which makes the race condition more likely to encounter.
Upvotes: 3