秀杰空间

  • 首页
  • 心情笔记
  • Linux/Unix C/C++
  • PHP
  • 我的项目
秀杰笔记
做些有意义的事情
  1. 首页
  2. Linux/Unix C/C++
  3. 正文

UNIX环境高级编程学习之第十一章线程-线程的创建、退出、等待、取消、分离

2016年9月7日 1079点热度 0人点赞 0条评论

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]

标签: UNIX环境高级编程
最后更新:2016年9月7日

秀杰

做些有意义的事情

点赞
< 上一篇
下一篇 >

文章评论

您需要 登录 之后才可以评论

秀杰

做些有意义的事情

标签聚合
socket protobuf 分布式 pb tuxedo UNIX环境高级编程 mac epoll select ubuntu zookeeper
最新 热点 随机
最新 热点 随机
C++使用protobuf快速入门简明教程 Mac安装Brew(Homebrew)国内镜像源加速 从sockaddr_storage结构中取IP地址和端口 [转载]分布式之数据库和缓存双写一致性方案解析 TPS和QPS的区别和理解 2018最新可靠好用的DNS服务器地址汇总
UNIX环境高级编程学习之第十六章网络IPC:套接字 - 非阻塞的Socket通信Poll模型(多路复用), 实用Socket通信模板 UNIX环境高级编程学习之第六章系统数据文件和信息-取所有用户名和UID, GID UNIX环境高级编程学习之第十一章线程-使用读写锁 zookeeper集群部署搭建 Supervisor进程管理工具的安装与使用入门 UNIX环境高级编程学习之第十五章进程间通信 - 信号量的使用(信号灯的使用, 计算信号灯)

COPYRIGHT © 2023 个人笔记. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang