Как собрать и проверить состояние выхода потока, когда поток отменен, используя pthread_cancel
Ниже программы я пытаюсь проверить состояние, используя PTHREAD_CANCELED
и другое указанное пользователем значение.
Для отмененного потока if(status == PTHREAD_CANCELED)
- это true, но для указанного пользователем выходного значения if(status == errNum)
- не true, это будет верно, если дескриптор if(status == *(int *)errNUM)
, но если я использую тот же способ, чтобы узнать значение PTHREAD_CANCELED
, используя *(int *)PTHREAD_CANCELED
это будет segfault, почему так?
Кстати, еще один вопрос: разрешено ли удалять из него такую же ветку pthread_cancel(pthread_self());
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg);
void *thread_func2(void *arg);
int errNum = 3;
pthread_t st_id;
int main()
{
pthread_t t_id, t_id2;
void *status;
// on success pthread_create return zero
if(pthread_create(&t_id,NULL,thread_func,NULL) != 0){
printf("thread creation failed\n");
return 0;
}
printf("thread created with id %u successfully\n",t_id);
st_id = t_id;
if(pthread_create(&t_id2,NULL,thread_func2,NULL) != 0){
printf("thread creation failed\n");
return 0;
}
printf("thread created with id %u successfully\n",t_id2);
if(pthread_join(t_id,&status) == 0){
printf("join success \n");
if(status == PTHREAD_CANCELED){
printf("Thread %u cancelled successfully,value =%u\n",t_id,*(int *)status);
}else if(status){
printf("thread %u exited with status %u\n",t_id,status);
}
}
else {
printf("join failed \n");
}
if(pthread_join(t_id2,&status) == 0){
printf("join success for tid2\n");
if(status == PTHREAD_CANCELED){
printf("Thread %u cancelled successfully, value = %u\n",t_id2,*(int *)status);
}else if(status){
printf("thread %u exited with status %u\n",t_id2,status);
}
}
else {
printf("join failed for tid2\n");
}
return 0;
}
void *thread_func(void *arg)
{
printf("Inside thread_func :%u\n",pthread_self());
sleep(3);
pthread_exit(0);
}
void *thread_func2(void *arg)
{
printf("Inside thread_func2 :%u\n",pthread_self());
pthread_cancel(st_id);
pthread_exit(&errNum);
}