简体   繁体   中英

Condition variable wait in child thread stops execution in main thread

I have class player with its own thread:

player.cpp

int soh::player::instance_count{ 0 };
int soh::player::current_player{ -1 };
std::mutex soh::player::mutex;
std::condition_variable soh::player::cv;

soh::player::player(std::string name)
    : name{ std::move(name) }
    , id{ soh::player::instance_count }
    , thread{ &soh::player::routine, this }
{
    ++soh::player::instance_count;
    std::cout << this->name << " created\n"; // prints player_0 created
}

soh::player::~player()
{
    --soh::player::instance_count;
    thread.join();
}

void soh::player::routine() 
{
    std::cout << soh::player::instance_count << '\n'; // prints 0
    std::unique_lock<std::mutex> lk(mutex);
    cv.wait(lk, [id = this->id]{return id == current_player;});

    std::cout << "Worker thread " << id << " is processing data\n";
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Worker thread " << id << " data processing completed\n";

    lk.unlock();
    cv.notify_all();
}

And when I try to spawn some objects of this type, main thread stops on creating the first one:

int main(int argc, char* argv[])
{
    soh::player{ "player_0" }; // <- main thread stops here
    soh::player{ "player_1" };
    {
        std::lock_guard<std::mutex> lk(soh::player::mutex);
        std::cout << "???\n";
        soh::player::current_player = 0;
    }
    soh::player::cv.notify_all();

    std::this_thread::sleep_for(std::chrono::seconds(2));

    return 0;
}

I've failed to figure out why this code doesn't. Any help is greatly appreciated!

soh::player{ "player_0" }; creates an unnamed temporary object that immidiatelly gets destroyed hanging at .join() because thread routine hangs at cv.wait . You should give it a name so will survive until it gets out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM