多线程的互斥锁的运用
2016-06-19 09:25
453 查看
1、互斥锁的初始化pthread_mutex_init()函数语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091815311-392200328.png)
2、互斥锁上锁、判断上锁、解锁、销毁锁pthread_mutex_函数语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091940222-1815888544.png)
代码分析:
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091815311-392200328.png)
2、互斥锁上锁、判断上锁、解锁、销毁锁pthread_mutex_函数语法
![](https://images2015.cnblogs.com/blog/899410/201606/899410-20160619091940222-1815888544.png)
代码分析:
/* thread_mutex.c */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define THREAD_NUMBER 3 /* 线程数 */ #define REPEAT_NUMBER 3 /* 每个线程的任务数 */ #define DELAY_TIME_LEVELS 10.0 /* 任务之间的最大时间间隔 */ pthread_mutex_t mutex; void* thrd_func(void* arg) { int thrd_num = (int)arg; int delay_time = 0, count = 0; int res; /* 互斥锁上锁 */ res = pthread_mutex_lock(&mutex); if(res) { printf("Thread %d lock failed\n", thrd_num); pthread_exit(NULL); } 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)); /* 互斥锁初始化 */ pthread_mutex_init(&mutex, 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 threads 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 joined failed\n", no); } /* 互斥锁解锁 */ pthread_mutex_unlock(&mutex); } pthread_mutex_destroy(&mutex); return 0; }
相关文章推荐
- IBM 计划在内部推行基于比特币的开源项目 Hyperledger
- IBM 计划在内部推行基于比特币的开源项目 Hyperledger
- 【EA】实体的生成
- 1075. PAT Judge (25)
- RecyclerView添加多个样式不同的Item布局
- 框架及测试用例写法
- 第16周学习进度条
- (2) Socket网络编程(C#)----同步传输字符串
- 第十六周学习进度
- 【译】.NET中六个重要的概念:栈、堆、值类型、引用类型、装箱和拆箱
- hibernate查询排序
- svn 回退/更新/取消至某个版本命令详解
- svn 回退/更新/取消至某个版本命令详解
- 第十六周学习进度
- 深入理解C#委托及原理
- 【原创】岗位作业书-程序员(六)
- 多线程的创建、退出、等待、删除语法
- PAT乙级练习题B1010. 一元多项式求导
- 个人总结
- 并查集小结