mutex 测试程序
来源:互联网 发布:腾讯代理绝地求生知乎 编辑:程序博客网 时间:2024/06/14 10:48
这段程序使用了 C++ 11 中的线程库(注意:编译时请不要加 -O 优化选项,否则空循环会被优化掉):
g++ -std=c++14 -Wall -pedantic -pthread main.cpp && ./a.out
// mutex::lock/unlock#include <iostream> // std::cout#include <thread> // std::thread#include <mutex> // std::mutexstd::mutex g_mtx; // mutex for critical sectionint g_flag = 1;void thread_run (int id){ g_mtx.lock(); ++g_flag; for(int i = 0; i < 100000000; ++i) {} --g_flag; std::cout << "thread #" << id << ": " << g_flag << '\n'; g_mtx.unlock();}#define NUM_THREAD 9int main (){ std::thread threads[NUM_THREAD]; // spawn NUM_THREAD threads: for (int i = 0; i < NUM_THREAD; ++i) threads[i] = std::thread(thread_run, i + 1); for (auto& th : threads) th.join(); return 0;}
不使用 mutex 是这样的:
thread #3: 9thread #1: 8thread #2: 7thread #8: 6thread #4: 5thread #9: 4thread #6: 3thread #7: 2thread #5: 1
在上面的输出中,为了不让 stdout 成为竞争资源,我们对 stdout 加锁,以防止出现错乱的输出:
void thread_run (int id){ ++g_flag; for(int i = 0; i < 100000000; ++i) {} --g_flag; g_mtx.lock(); std::cout << "thread #" << id << ": " << g_flag << '\n'; g_mtx.unlock();}
使用 mutex 是这样的:
thread #1: 1thread #2: 1thread #3: 1thread #5: 1thread #4: 1thread #6: 1thread #7: 1thread #8: 1thread #9: 1
C++ 11, C++ 14 可以到这里在线编译:
http://coliru.stacked-crooked.com/
0 0
- mutex 测试程序
- Mutex测试
- Linux驱动:互斥锁mutex测试
- mutex加锁和解锁性能测试
- boost mutex lock学习及测试
- CAS锁与MUTEX锁性能测试
- Mutex
- Mutex
- mutex
- Mutex
- Mutex
- Mutex
- Mutex
- mutex
- Mutex
- C# Mutex实现程序单实例运行
- 使用sysbench对Oracle做基准测试(四) MUTEX
- C#中lock,Monitor和Mutex的测试代码
- CGContextRef 小结
- Java @override报错的解决方法
- .net调用平台命令
- Xamarin体验:使用C#开发iOS/Android应用
- Golang开发环境搭建-Vim篇
- mutex 测试程序
- Android EditText/TextView使用SpannableString显示复合文本
- FJUTOJ 校赛J 第十集 原来这一切都是真的 (树形概率dp)
- C++快速排序(随机值元法)
- Log4j的输出日志级别
- maven项目在eclipse中运行clean test 等报错
- 关于动态代理模式
- Linux 上tomcat的安装
- objc block的介绍和使用