摘要: 线程中的异常可以使用 std::rethrow_exception 抛给主线程 问题分析:一个线程中抛出的异常是没法被另一个线程捕获的。假如我们在主线程中创建一个子线程,子线程中的函数抛出了异常,主线程的 catch 是不会触发,如下, #include<iostream> #include<thr 阅读全文
posted @ 2022-05-22 18:37 strive-sun 阅读(398) 评论(0) 推荐(0) 编辑
摘要: 有时候使用 std::atomic 比使用 mutexes 更高效 问题分析:使用多线程更新一些简单数据时,比如 int 型,bool 型等等,可以使用 std::atomic,这比 mutex 来得更为高效。 比如,我们一般这样用: int counter; .... mu.lock(); cou 阅读全文
posted @ 2022-05-22 15:20 strive-sun 阅读(82) 评论(0) 推荐(0) 编辑
摘要: 不要重复获取同一个锁 问题:在获得一个锁并且没有释放该锁的前提下,再次尝试获取该锁会报错。 比如, #include <iostream> #include <thread> #include <mutex> std::mutex mu; static int counter = 0; void S 阅读全文
posted @ 2022-05-22 15:13 strive-sun 阅读(80) 评论(0) 推荐(0) 编辑