std::unique_lock也可以提供自动加锁、解锁功能,比std::lock_guard更加灵活

https://www.cnblogs.com/xudong-bupt/p/9194394.html

 

#include <QCoreApplication>
#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(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    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 a.exec();
}

 

相关文章:

  • 2022-01-26
  • 2021-09-30
  • 2021-12-14
  • 2022-12-23
  • 2021-10-16
  • 2021-10-04
  • 2022-01-11
猜你喜欢
  • 2022-12-23
  • 2021-04-29
  • 2021-09-06
  • 2021-08-25
  • 2022-01-10
  • 2021-08-21
  • 2022-01-01
相关资源
相似解决方案