线程同步——互斥量
2016-07-15 09:21
176 查看
互斥量的使用:
// 线程同步之互斥量 #include <iostream> #include <string> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> using namespace std; // 全局变量,两个线程都可以修改,因此修改的时候需要加锁 int g_Value = 0; // 互斥量 pthread_mutex_t lock; // 线程函数1 void* thread_func1(void* data) { int i = 0; while(i < 10) { ++i; // 加锁 pthread_mutex_lock(&lock); // 修改全局变量 ++g_Value; // 解锁 pthread_mutex_unlock(&lock); } return 0; } // 线程函数2 void* thread_func2(void* data) { int i = 0; while(i < 10) { ++i; // 加锁 pthread_mutex_lock(&lock); // 修改全局变量 ++g_Value; // 解锁 pthread_mutex_unlock(&lock); } return 0; } // 主函数 int main(int argc,char* argv[]) { // 初始化互斥量 pthread_mutex_init(&lock,0); // 定义两个线程id pthread_t thd1,thd2; // 创建两个线程 pthread_create(&thd1,0,thread_func1,0); pthread_create(&thd2,0,thread_func2,0); // 等待两个线程运行结束 pthread_join(thd1,0); pthread_join(thd2,0); // 销毁互斥量 pthread_mutex_destroy (&lock); cout << g_Value<<endl; return 0; }
相关文章推荐
- 关于数字、数据处理的几个PHP函数汇总
- Gym 100735 - I. Yet another A + B
- Codeforces697B Barnicle 模拟
- C语言putc()函数:写文件函数(将一指定字符写入文件中)
- 安卓字体渲染器
- LoadRunner之并发用户数与迭代关系
- mysql的备份
- hitTest:withEvent使用
- Looper、MessageQueue、Handler三者关系理解
- putc
- 32、正则表达式
- mac快捷键
- Windows下Nginx的启动、停止等基本命令
- python求pi的方法
- iOS开发中WiFi相关功能总结
- C语言ungetc()函数:把字符退回到输入流
- KJFrameForAndroid 资料——KJBitmap使用方法
- ungetc
- clearerr
- nohup不输出日志信息的方法及linux重定向