【工作笔记】互斥锁
2017-02-22 15:42
363 查看
代码说明
当代码中出现多个线程需要操作一个同一个变量时,需要互斥锁。下面的代码实现了,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); } }
相关文章推荐
- 【工作笔记】Spring mvc多文件上传
- 工作笔记
- squid工作笔记 - 1
- Linux Kernel Development 笔记(七)下半部处理以及延迟工作
- #工作笔记 Android 各类统计数据
- 我的Android工作笔记
- 日常工作笔记--linux命令大全
- [工作笔记之三] 通过adb查看android手机CPU和内存占用情况
- 工作笔记3:关于表单验证validate插件的使用
- Hadoop学习笔记(六):Hadoop读写文件时内部工作机制
- Agar工作笔记(更新中...)
- (工作笔记)table中td内容换行问题
- Spring Insight 笔记 2 Spring insight 如何工作?
- 2017.3.27日工作笔记
- 【工作笔记】浏览器后退响应及关于input标签的一些说明
- 工作中一些比较奇怪的产品需求笔记
- rabbitMQ消息服务器学习笔记(java)2 工作队列
- 工作笔记之--ordupdate
- mysql数据库+java实现事务控制工作笔记
- squid阅读笔记一 - squid工作流程