Как выполнить действие после завершения потока

void print()
{
    cout<<"Hello!!";
}
void print2()
{
    while(true) cout << "while";
}
void test()
{
this_thread::sleep_for(chrono::milliseconds(200));
th = make_unique<thread>([&]() {
    this_thread::sleep_for(chrono::milliseconds(800));
    cout << "Connection is successful! Wait...";
    this_thread::sleep_for(chrono::milliseconds(1000));
    cout << "Setting up the environment!";

    this_thread::sleep_for(chrono::milliseconds(400));
    cout <<"All is done!";

});
print();
if (0 != th.get())th.get()->join();
}
    

Как мне вызвать метод print(), который находится в области видимости join() после выполнения потока th. А так же, чтобы одновременно выполнялся метод print2()

int main()
{
    test();
    print2();
    cout<< "Hello 2222";
    return 1;
}

Ответы (1 шт):

Автор решения: Harry

Вот это — похоже на то, что вы хотите?

#include <iostream>
#include <thread>

using namespace std;

void print()
{
    cout<<"Hello!!";
}

void print2()
{
    for(int i = 0; i < 8; ++i)
    {
        cout << "meanwhile...\n";
        this_thread::sleep_for(chrono::milliseconds(200));
    }
}

thread test()
{
    this_thread::sleep_for(chrono::milliseconds(200));
    return thread([&]() {
        this_thread::sleep_for(chrono::milliseconds(400));
        cout << "Connection is successful! Wait...\n";
        this_thread::sleep_for(chrono::milliseconds(400));
        cout << "Setting up the environment!\n";
        this_thread::sleep_for(chrono::milliseconds(400));
        cout <<"All is done!\n";});
}

int main(int argc, char * argv[])
{
    auto t = test();
    print2();
    t.join();
    print();
}
→ Ссылка