多线程的创建、退出、等待、删除语法
2016-06-19 09:15
513 查看
1、多线程创建pthread_create()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090807534-1830079040.png)
2、多线程退出pthread_exit()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090903896-1347830070.png)
3、多线程等待pthread_join()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090944070-1126625826.png)
4、多线程删除pthread_cancel()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091026040-853917786.png)
代码分析:
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090807534-1830079040.png)
2、多线程退出pthread_exit()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090903896-1347830070.png)
3、多线程等待pthread_join()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619090944070-1126625826.png)
4、多线程删除pthread_cancel()的语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091026040-853917786.png)
代码分析:
/* thread.c */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define THREAD_NUMBER 3 /*线程数*/ #define REPEAT_NUMBER 5 /*每个线程中的小任务数*/ #define DELAY_TIME_LEVELS 10.0 /*小任务之间的最大时间间隔*/ void *thrd_func(void *arg) { /* 线程函数例程 */ int thrd_num = (int)arg; int delay_time = 0; int count = 0; printf("Thread %d is starting\n", thrd_num); for (count = 0; count < REPEAT_NUMBER; count++) { delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1; sleep(delay_time); printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time); } printf("Thread %d finished\n", thrd_num); pthread_exit(NULL); } int main(void) { pthread_t thread[THREAD_NUMBER]; int no = 0, res; void * thrd_ret; srand(time(NULL)); for (no = 0; no < THREAD_NUMBER; no++) { /* 创建多线程 */ res = pthread_create(&thread[no], NULL, thrd_func, (void*)no); if (res != 0) { printf("Create thread %d failed\n", no); exit(res); } } printf("Create treads success\n Waiting for threads to finish...\n"); for (no = 0; no < THREAD_NUMBER; no++) { /* 等待线程结束 */ res = pthread_join(thread[no], &thrd_ret); if (!res) { printf("Thread %d joined\n", no); } else { printf("Thread %d join failed\n", no); } } return 0; }
相关文章推荐
- PAT乙级练习题B1010. 一元多项式求导
- 个人总结
- 并查集小结
- 使用开放的showapi接口小技巧
- 算法之排序(选择、冒泡、插入)
- Git(转载)
- C#委托与事件学习笔记
- Spring Security xsd 异常
- 文章标题
- Arduino 卡片6报警器
- 软件工程师必读技术书籍推荐
- range与xrange
- 数组中的逆序对37
- phpstrom2016.1.2运行项目设置
- Sublime Text3注册码(可用)
- 设计模式整理_命令模式
- Android总结--SQLite
- shell脚本设置守护进程
- 判别模型(Discriminative model)和生成模型(Generative model)
- 某P保护之调戏权限清0的学习。