将信号量与 std::stop_token 组合

发布于 2025-01-20 11:06:29 字数 544 浏览 2 评论 0原文

所以我有一些消费者,它是一个单独的线程并等待信号量。如果信号量被发布,它会做一些工作,然后返回等待信号量。

因为我想变得现代,所以我决定使用 std::jthread。现在我有了这个 std::stop_token 东西,我的代码看起来像这样:

void thread(std::stop_token stopToken)
{
    while(true) {
        bool success = this->sem.try_acquire_for(std::chrono::milliseconds(500));
        if (stopToken.stop_requested()) {
            return;
        }
        if (!success) {
            continue;
        }
        // Do the actual work
}

不知何故,这感觉很笨重。如果我可以同时等待信号量和停止令牌,那就太好了。或者修改 jthread,以便它在销毁时发布信号量。这样的事情可能吗?

So I have some consumer, which is a seperate thread and waits on a semaphore. If the semaphore gets posted, it does some work and then goes back to waiting on the semaphore.

Because I want to be modern, I decided to use an std::jthread. Now I have this std::stop_token thing and my code looks like this:

void thread(std::stop_token stopToken)
{
    while(true) {
        bool success = this->sem.try_acquire_for(std::chrono::milliseconds(500));
        if (stopToken.stop_requested()) {
            return;
        }
        if (!success) {
            continue;
        }
        // Do the actual work
}

Somehow this feels way to clunky. It would be nice if I could wait on both the semaphore and the stoptoken. Or maybe modify jthread so that it will post the semaphore on destruction. Is something like that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文