Search code examples
c++multithreadingdetach

why does detach thread get no output message?


I am testing a cpp code as below, and got one very confusing phenomena, below code does not print "label" string. Could anyone explain it? really thanks for your help!

class Data {
public:
  Data() { std::cout << __FUNCTION__ << std::endl; }
  ~Data() { std::cout << __FUNCTION__ << std::endl; }
  void show() { std::cout << label << std::endl; }

private:
  std::string label{"label"};
};

int main() {
  auto data = std::make_shared<Data>();
  std::thread t([=]() mutable{
    data->show();
  });

  t.detach();
}

Solution

  • As already mentioned in comment section by Mat, nothing is preventing the program to end before thread even begins.

    Change t.detach() to t.join().

    From cppreference on join

    waits for a thread to finish its execution