C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::thread::first_ever

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 30 Apr 2023 13:14:08 +0100
On Sun, Apr 30, 2023 at 12:53 PM Mike Reed wrote:
>
> Sorry for my ignorance here but I'm struggling to imagine how what you call the first ever thread
> can terminate without the program terminating. Surely if the "main()" thread terminates it has to
> leave main() and isn't that the beginning of the end of the program?


I just realised now that this isn't supposed to happen. It's possible
with pthreads, but you'll be missing all the destructors and 'atexit'
stuff that would normally be invoked after main:

    https://godbolt.org/z/rcKf6r9Tf

#include <iostream>
#include <thread>
#include <chrono>
#include <utility>

#include <pthread.h>

int main(void)
{
    std::thread t([]
      {
        for ( unsigned i = 0u;; )
        {
            std::cout << i++ << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(500u));
        }
      });

    t.detach();

    pthread_exit(nullptr);

    std::unreachable();
}

Received on 2023-04-30 12:14:17