Linux多线程编程之创建两个子线程,分别执行子线程函数(注意编译方式)
2017-12-07 20:41
1136 查看
#include <stdio.h> #include <pthread.h> //Linux多线程编程之创建两个子线程,分别执行子线程函数(注意编译方式) /* int pthread_join(pthread_t thread, void **retval); int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); void pthread_exit(void *retval); pthread_t pthread_self(void); */ /* linux中线程属于第三方库开发 安装线程库man手册: sudo apt-get install manpages manpages-dev sudo apt-get install manpages-posix-dev 编译: gcc -o bin src.c -lpthread //指定线程库链接 */ //线程1执行函数 void *pthread_1(void *arg) { printf("pthread 1 run...\n"); int i =2; while(i--){ printf("thread1 i =%d\n",i); sleep(1); } pthread_exit(NULL); return NULL; } //线程2执行函数 void *pthread_2(void *arg) { printf("pthread 2 run..\n"); sleep(3); printf("pthread 2 exit\n"); pthread_exit(NULL); return NULL; } int main(void) { //打印线程id号 printf("main thread tid = 0x%x\n",pthread_self()); //创建子线程1 pthread_t tid1;//定义子线程标识符 pthread_create(&tid1,NULL,pthread_1,NULL);//pthread_1即线程执行函数 //创建子线程2 pthread_t tid2;//定义子线程标识符 pthread_create(&tid2,NULL,pthread_2,NULL);//pthread_2即线程执行函数 //阻塞等待子线程结束,回收子线程结束8kb物理内存 pthread_join(tid1,NULL); pthread_join(tid2,NULL); printf("child pthread exit\n"); //sleep(5); printf("main pthread exit\n"); pthread_exit(NULL); //结束主线程 return 0; } //编译:gcc 38_pthread.c -lpthread /* $ ./a.out main thread tid = 0xb75c26c0 pthread 2 run.. pthread 1 run... thread1 i =1 thread1 i =0 pthread 2 exit child pthread exit main pthread exit */
相关文章推荐
- 创建执行线程的方式三:实现 Callable 接口
- 【Java并发编程】Thread方式创建线程
- LINUX多线程编程之创建,等待,取消线程
- Java多线程编程小结+java中创建线程的的几种方式
- linux多线程编程1--线程的创建
- 并发编程学习总结(一) :java 创建线程的三种方式的优缺点和实例(转载自:http://blog.csdn.net/u011784767/article/details/51315007)
- 多线程——用创建线程的两种方式分别解决经典窗口卖票问题
- [Java并发编程]-创建线程的两种方式及区别
- java并发编程实践 part 01 --> 线程创建方式
- 以编程方式创建次线程
- JAVA并发编程学习笔记------线程的三种创建方式
- C# 多线程编程基础——怎么创建和执行多个线程
- oracle编程入门笔记2015-01-18--执行计划中的索引扫描方式说明
- 如何使用 ADO.NET 和 Visual C# .NET 以编程方式创建 SQL Server 数据库
- 使用xib方式创建UITableViewCell,设置Label自动换行注意事项
- java并发编程---如何创建线程以及Thread类的使用
- POSIX定时器-线程方式创建定时器
- 创建线程的几种方式
- 进程方式执行CMD命令及使用CMD命令一次创建多级录
- 线程创建时内存注意释放