UNIX环境高级编程学习之第十一章线程-线程的创建、退出、等待、取消、分离
[code lang=”cpp”]#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void* thread_fun(void* arg) // 线程执行函数1
{
printf("fun:hello world!/n");
return (void*)1;
}
void* thread_fun2(void* arg) // 线程执行函数2
{
printf("fun 2:tid = %ul/n", pthread_self()); // pthread_self() 调用当前线程ID
pthread_exit((void*) 2); // 线程退出
}
void* thread_fun3(void* arg) // 线程执行函数3
{
while (1)
{
printf("fun 3:tid = %ul/n", pthread_self());
sleep(5);
}
return (void*)3;
}
int main(int argc, char* argv[])
{
const int n = 3;
int i, ret;
void* tret;
pthread_t tid[n];
ret = pthread_create(&tid[0], NULL, thread_fun, NULL); // 线程创建
if (ret != 0)
{
printf("pthread_create 0 Error/n");
}
ret = pthread_create(&tid[1], NULL, thread_fun2, NULL); // 线程创建
if (ret != 0)
{
printf("pthread_create 1 Error/n");
}
ret = pthread_create(&tid[2], NULL, thread_fun3, NULL); // 线程创建
if (ret != 0)
{
printf("pthread_create 2 Error/n");
}
ret = pthread_detach(tid[2]);// 线程分离, 线程分离后,底层资源立即回收,再用pthread_join取状态会报错。
if (ret != 0)
{
printf("pthread_cancel Error/n");
}
ret = pthread_cancel(tid[2]);// 线程取消
if (ret != 0)
{
printf("pthread_cancel Error/n");
}
for (i = 0;i < n;i++)
{
ret = pthread_join(tid[i], &tret); // 取线程退出状态
if (ret != 0)
{
printf("%d. pthread id:%ul, pthread_join Error!/n",
i, tid[i]);
}else{
printf("%d. pthread id:%ul, pthread_fun return value:%d /n",
i, tid[i], (int)tret);
}
}
sleep(15);
return 0;
}

[/code]

发表评论