voidincrease_proxy(int time, int id){ for (int i = 0; i < time; i++) { std::lock_guard<std::mutex> lk(mtx); if (id == 1) { throw std::runtime_error("throw excption...."); } // 当前线程休眠1毫秒 std::this_thread::sleep_for(std::chrono::milliseconds(1)); counter++; } }
voidincrease(int time, int id){ try { increase_proxy(time, id); } catch (const std::exception& e){ std::cout << "id:" << id << ", " << e.what() << std::endl; } }
#include<mutex> #include<thread> structbank_account { explicitbank_account(int balance) : balance(balance) {} int balance; std::mutex m; };
voidtransfer(bank_account &from, bank_account &to, int amount){ // avoid deadlock in case of self transfer if(&from == &to) return; // lock both mutexes without deadlock std::lock(from.m, to.m); // make sure both already-locked mutexes are unlocked at the end of scope std::lock_guard<std::mutex> lock1(from.m, std::adopt_lock); std::lock_guard<std::mutex> lock2(to.m, std::adopt_lock);
plus g_i by func thread 140476623930944 plus g_i by func thread 140476623930944 wait for exit // 表示子线程等待唤醒 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 plus g_i by main thread 140476623935296 func thread exit // 子线程被唤醒 g_i = 200
信号量
因为一开始我也不知道该怎么去写信号量,所以打开了万能的搜索引擎,看到了关于 C++ 不支持信号量这样的东西 6。如果想实现信号量,可以通过互斥量和条件变量来实现。而关于信号量和互斥量的区别,在这篇文章中已经写明了。那么来实现一个信号量的类 7:
std::thread::id thread_id = std::this_thread::get_id(); std::string now = FormatTimeNow("%H:%M:%S"); { std::lock_guard<std::mutex> lock(g_io_mutex); std::cout << "Thread " << thread_id << ": wait succeeded" << " (" << now << ")" << std::endl; } // Sleep 1 second to simulate data processing. std::this_thread::sleep_for(std::chrono::seconds(1));
g_semaphore.Signal(); }
intmain(){ std::vector<std::thread> v; for (std::size_t i = 0; i < 3; ++i) { v.emplace_back(&Worker); } for (std::thread& t : v) { t.join(); } return0; }
信号量的值为 3,表示能同时申请 3 个资源
当一个线程申请资源后,即执行了 wait 操作,count_ 取值递减,表示有一个资源被占用
当 count_ 取值小于 0 时,调用条件变量的 wait 方法,当先线程等待有了资源被唤醒
当一个线程释放资源后,执行了 signal 操作,count_ 取值递增,表示有一个资源被释放,并执行 notify_one 方法,即唤醒一个等待的线程