线程退出
线程的退出方式有三种:
执行完成后隐式退出;
由线程本身显示调用 pthread_exit (void * retval);函数退出。其中,参数 retval 用于保存线程退出状态
被其他线程用 pthread_cance (pthread_t thread);函数终止。在某线程中调用此函数,可以终止由参数 thread 指定的线程。
实例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_t tidp, tidp2; // 线程ID
void *thread1(void *arg)
{
int *num;
num = (int *)arg; // 存放传递的参数
printf("I‘m thread1, ID is %u\n",pthread_self()); // 打印线程自己的ID
printf("Receive parameter is %d \n",*num); // 打印收到的参数
printf("I'm waitting to be cancenl!\n");
sleep(20); // 等待线程2 将它结束
return (void *)0; // 如果,线程2没有将其结束,返回0
}
void *thread2(void *arg)
{
int error;
printf("I'm thread2. I Will to Cancel thread %u\n",tidp);
error = pthread_cancel(tidp); // 取消线程 1
if(error<0)
{
printf("Cancel thread %u failed!\n",tidp);
return (void *)-1;
}
else
{
printf("Cancel thread %u sucessfully! It will not return 0!\n",tidp); // 因为线程2将线程1取消了,所以线程1不能正常返回0
}
return 0;
}
int main(int argc, char *argv[])
{
int error;
void* r_num1,*r_num2;
int test = 4;
int *attr = &test;
error = pthread_create(&tidp,NULL,thread1,(void *)attr); // 创建新线程,并传递参数(void *)attr
if(error)
{
printf("pthread_create is created is not created ... \n");
return -1;
}
error = pthread_create(&tidp2,NULL,thread2,NULL);
if(error)
{
printf("pthread_create is created is not created ... \n");
return -1;
}
error = pthread_join(tidp2,&r_num2); // 阻塞在此处,直到线程2返回
error = pthread_join(tidp,&r_num1); // 阻塞在此处,直到线程1返回
sleep(1);
printf("Thread1 return %d\n",(int)r_num1); // 线程1的返回值,如果线程1被线程2 取消,则返回值不是0
printf("Thread2 return %d\n",(int)r_num2); // 线程2的返回值
return 0;
}
|