mardi 13 décembre 2022

cpp thread detach position?

my simple test code here:

// t.cpp

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

void fcn()
{
    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"hihi" << float(i++)<<std::endl;
    }
}

std::thread t(fcn);

t.detach(); // detach position A

int main()
{
    // t.detach(); // detach position B
    
    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"yoyo" << float(i++)<<std::endl;
    }

}

compile and run by g++ ./t.cpp -o t -lpthread; ./t;

when detach at position A got compile error error: ‘t’ does not name a type | t.detach();, but detach at position B is ok.

why is this different?

my situation is that i wish to move the fcn() and std::thread t(fcn) as well as t.detach() into a standalone header file later (for a better orginazation of the project) thanks

Aucun commentaire:

Enregistrer un commentaire