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
原创粉丝点击