0
#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完成甚至发生异常

4

1 回答 1

0

几件事:

  1. 该对象只会在作用域std::unique_lock ul结束时被销毁。func当您抛出异常并捕获它时,只有try ... catch块内的对象被破坏,但ul在该块之外定义,因此它不会被破坏。
  2. des == "T1"比较字符串指针,而不是字符串内容。truedes指向 string时,它可能会也可能不会屈服T1。您应该将 C 风格的字符串与 进行比较std::strcmp,例如!std::strcmp(des, "T1").
于 2020-12-10T11:57:32.510 回答