子线程中的条件变量等待停止在主线程中执行

Condition variable wait in child thread stops execution in main thread

我有 class 个播放器有自己的线程:

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();
}

当我尝试生成一些此类对象时,主线程在创建第一个对象时停止:

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;
}

我没弄清楚为什么这段代码没有。非常感谢任何帮助!

soh::player{ "player_0" }; 创建一个未命名的临时对象,该对象在 .join() 处立即被销毁,因为线程例程在 cv.wait 处挂起。你应该给它起一个名字,这样它就会一直存在,直到它超出范围。