خرید بک لینک

I was reading a (quite old) book on POSIX API, and in the chapter on threads it says that on return from main() all the threads (including detached ones) are terminated.

I would expect that std::thread::detach() internally uses POSIX threads API, and yet it seems that a detached std::thread is sort of joined with the main() thread (or the main process really), after the main() function returns on Ubuntu 26.04.

For example, the code below blocks on a read from std::cin and, if I write anything in the terminal, then the detached thread displays it via std::cout <<"Detached thread: you entered: "<< s << std::endl.

Does it mean that std::thread::detach() does not use the POSIX version of detach, or the book I'm reading is outdated as far as POSIX threads are concerned?

#include<thread>
#include<iostream>
#include<string>

struct Global {
  ~Global(){
      std::cout << "global variables destroyed...n" << std::flush; 
  }
} global;

int main(){
      {
         std::thread t([]{  
            std::string s;           
            std::getline(std::cin,s);
            std::cout <<"Detached thread: you entered: "<< s << std::endl;
         });
         t.detach();
      }
      auto delay = 3; 
      std::cout << "Waiting for the thread to start ("
                <<  delay 
                << "s)...n"
                <<std::flush; 
      std::this_thread::sleep_for(std::chrono::seconds(delay));
      std::cout << "Done... (Try to press Enter)" << std::endl;
      
}

This is the output of the program:

Waiting for the thread to start (3s)... Done... (Try to press Enter)

global variables destroyed...

THIS TEXT WAS WRITTEN BY ME
Detached thread: you entered: THIS TEXT WAS WRITTEN BY ME

Edit. As suggested in a comment by Igor Tandetnik, as well as in the answer by Jerry Coffin, the observed behavior seems to be caused by the lock acquired by std::cin (or std::FILE object behind stdin). More specifically, I noticed that adding

std::cin.sync_with_stdio(false);

makes the thread detach without blocking the process.

برچسب: نویسنده: استخدام کار تاريخ: شنبه 7 شهريور 1405 ساعت: 2:40

صفحه بندی