std::lock_guard

/*
std::lock_guard:更方便线程对于互斥量的上锁操作
std::lock_guard:在定义一个lock_guard时上锁,保证在析构或者异常时解锁
*/
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_error

std::mutex mtx;

void print_even (int x) {
    if (x%2==0) std::cout << x << " is even\n";
    else throw (std::logic_error("not even"));
}

void print_thread_id (int id) {
    try {
        // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
        std::lock_guard<std::mutex> lck (mtx);//对mtx上锁,保证在析构时解锁
        print_even(id);
    }
    catch (std::logic_error&) {
        std::cout << "[exception caught]\n";
    }
}

int main ()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i=0; i<10; ++i)
        threads[i] = std::thread(print_thread_id,i+1);

    for (auto& th : threads) th.join();
    getchar();
    return 0;
}

具体可看http://www.cnblogs.com/haippy/p/3237213.html

posted @ 2014-04-18 00:21  zzyoucan  阅读(607)  评论(0编辑  收藏  举报