【问题标题】:Condition variable wait in child thread stops execution in main thread子线程中的条件变量等待在主线程中停止执行
【发布时间】:2020-05-18 21:18:41
【问题描述】:

我有自己的线程的类播放器:

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

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

【问题讨论】:

    标签: c++ multithreading c++11 concurrency condition-variable


    【解决方案1】:

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

    【讨论】:

    • 天哪,我不敢相信我没有发现这一点。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2013-05-05
    • 2023-03-09
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多