1 线程退出函数
#include <pthread.h>
void pthread_exit(void *value_ptr);
2 通过线程id等待指定线程退出的线程函数。
#include <pthread.h>
int pthread_join(pthread_t thread, void **value_ptr);
3 获取线程自身的线程id
#include <pthread.h>
pthread_t pthread_self(void);
下面直接附上代码。
线程2等待线程1退出。并获取 pthread_exit传过来的指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/statfs.h>
#include <pthread.h>
//主动关闭其他线程。
//获取指定线程的退出状态
static void * proc_func_exit(void *);
static void * proc_func_join(void *);
int main()
{
pthread_t th1 = -1;
pthread_t th2 = -1;
int ret = -1;
ret = pthread_create(&th1,NULL,proc_func_exit,NULL);
if(0 != ret)
{
return -1;
}
ret = pthread_create(&th2,NULL,proc_func_join,&th1);
if(0 != ret)
{
return -1;
}
while(1)
{
sleep(0xfff);
}
return 0;
}
static void * proc_func_exit(void *pArg)
{
// 获取自身的线程id
pthread_t pth_id = -1;
char *str = NULL;
str = (char *)malloc(100);
if(NULL == str)
{
return (void*)0;
}
pth_id = pthread_self();
printf("\n*** pthread_id = %d****",pth_id);
snprintf(str,100,"I am Exit! pthread_id = %d",pth_id );
//线程退出 pthread_exit
pthread_exit((void *)str);
return (void *)0;
}
static void * proc_func_join(void *pArg)
{
char *str = NULL;
pthread_t pth_id = -1;
if(pArg == NULL)
{
return (void *)0;
}
pth_id = *((pthread_t *)(pArg));
pthread_join(pth_id ,&str);
if(str != NULL)
{
printf("\nRecv:%s\n",str);
free(str);
}
return (void *)0;
}