将信号量与 std::stop_token 组合
所以我有一些消费者,它是一个单独的线程并等待信号量。如果信号量被发布,它会做一些工作,然后返回等待信号量。
因为我想变得现代,所以我决定使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论