#include <iostream>
#include <vector>
#include <thread>
#include<mutex>
using namespace std;
mutex m;
int count;
void
func (const char *des)
{
std::unique_lock < mutex > ul (m);
cout << "in :" << des << endl;
try
{
if (des == "T1")
throw "T1";
}
catch ( ...)
{
cout << "catched" << endl;
}
this_thread::sleep_for (10 s);
cout << "out of func" << endl;
}
int
main ()
{
// Constructing two threads and run it. Does not block execution.
thread t1 (func, "T1");
thread t2 (func, "T2");
cout << "main, t1 and t2 functions now execute concurrently...\n";
// synchronize threads
t1.join (); // Makes the main thread wait until t1 finishes
t2.join (); // Makes the main thread wait until t2 finishes
}
预期输出:在 T1 中捕获异常 T1 在 T2 中进入等待状态(因为唯一锁将解锁互斥锁,因此 T2 可以在 T1 完成任务的情况下开始工作) in :T2 out of func out of func
当前输出:在 T1 异常中捕获 T1 进入等待状态 out of func in :T2 out of func
为什么tread 2等待线程1完成甚至发生异常