LaLaAsDev
LaLaAsDev

Reputation: 315

How can I detect std::thread was terminated as async?

I'm a Java engineer but I need to migrate my Java code to C++.

In C++:

void foo(){
    thread t(&loading_function);
    t.detach();
}

void loading_function(){
    while(true){
    //..some loading operations
    }
}

//I want to call after loading_function NOT in main thread like t.join();
void loading_after(){  
    //..loading after handling
}

I want to handling after thread t was end of its process.

Like this Java code:

public class Test implements Runnable{
    public void foo(){
        Thread loading_thread = new Thread(this);
        loading_thread.start();
    }

    public void run(){
        while(true){
            //..some loading operations
        }
        loading_after();
    }

    public void loading_after(){
        //..loading after handling
    }
}

How can I do that?

Upvotes: 1

Views: 110

Answers (1)

rozina
rozina

Reputation: 4232

Based on the description on how std::thread::detach() works, I don't think you can detect when it ends, unless you make your loading_function() signal to the outside world that is has ended. There seems to be no built in mechanism for a detached std::thread to signal it has ended. I might be wrong, I have little experience with std::thread.

Alternative would be to make a function that does both loading_function() and loading_after() and pass that function to the std::thread object.

void loading_function()
{
    while(true)
    {
        //..some loading operations
    }
}

//I want to call after loading_function NOT in main thread like t.join();
void loading_after()
{  
    //..loading after handling
}

void load()
{
    loading_function();
    loading_after();
}

void foo()
{
    thread t(&load);
    t.detach();
}

Upvotes: 1

Related Questions