【工作笔记】互斥锁
来源:互联网 发布:java高级工程师技能树 编辑:程序博客网 时间:2024/06/10 01:35
代码说明
当代码中出现多个线程需要操作一个同一个变量时,需要互斥锁。下面的代码实现了,globVar增加200000次,一个线程增加10000次。互斥锁保证globVar是20000。代码在DEV C++上测试通过。
代码实例
#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <semaphore.h>void *thread_function(void *arg);void *thread_function1(void *arg);void *thread_function2(void *arg);long long globVar = 0;pthread_t a_thread;pthread_t thread1;pthread_t thread2;/* 互斥锁 */pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;int main(){ int res = 0; int *pRet; /* 创建新线程1 */ res = pthread_create(&thread1, NULL, thread_function1, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } /* 创建新线程2 */ res = pthread_create(&thread2, NULL, thread_function1, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } /* 线程阻塞 */ pthread_join(thread1, &pRet); pthread_join(thread2, &pRet); /* 打印最后的globVar值 */ printf("globVar=%d", globVar); return 0;}void *thread_function1(void *arg){ int i = 1; int locVar=0; for (i = 1; i <= 10000; i++) { /* 上锁 */ pthread_mutex_lock(&mtx); globVar++; /* 解锁 */ pthread_mutex_unlock(&mtx); }}
0 0
- 【工作笔记】互斥锁
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- 工作笔记
- ?c#把一行数据插入到datatable里面去?
- TOKEN+签名验证
- 寒假第一次录一个小小的模拟慕课视频吧~<关于函数定义和调用>
- ubuntu windows远程桌面连接xrdp相关问题
- select的if选择
- 【工作笔记】互斥锁
- Android 5.0共享元素学习总结
- Mysql 5.7 忘记密码或重置密码
- armeabi和armeabi-v7a
- pycharm激活码
- Nplot,.Net图表开源框架
- 【SAP HANA】SAP HANA开篇
- Reverse Bits
- PAT乙级1006 换个格式输出整数