2020-08-30 class mutex 互斥锁 (C++1

2020-08-30  本文已影响0人  Wonton_skin

// mutex::lock/unlock
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex

std::mutex mtx;  // mutex for critical section

void  print_thread_id (int id)  {
    //critical section (exclusive access to std::cout signaled by locking mtx):
    mtx.lock();
    std::cout << "thread #" << id << '\n';
    mtx.unlock();
}

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();
    return  0;
}


#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex

std::mutex mtx; // mutex for critical section
void print_block (int n,char c)
{
    // critical section (exclusive access to std::cout signaled by locking mtx):
    mtx.lock();
    for (int i = 0; i < n; ++i)  {  std::cout << c;  } 
    std::cout << '\n';
    mtx.unlock();
}

int main ()
{
     std::thread th1 (print_block,50,'*');
     std::thread th2 (print_block,50,'$');
     
     th1.join();
     th2.join();
     
    return 0;


#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);
        print_even(id);
    } catch (std::logic_error&) {
        std::cout << "[exception caught]\n";
    }
}

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

    for (auto& th : threads)   th.join();

return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读