C ++中的自定义阻止功能 [英] Custom blocking function in C++

查看:170
本文介绍了C ++中的自定义阻止功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于 while(true)和阻止功能的三个线程创建应用程序模型。

I'm creating application model with three threads based on while(true) and a blocking function.


  1. 事件线程 - 等待用户输入,被SDL_WaitEvent阻止

  2. Socked线程 - 等待服务器中的数据,阻止套接字阻止。

  3. 渲染线程 - 从缓冲区呈现数据,不被阻止。

我有一个渲染线程的问题 - 我需要一个阻塞功能,例如阻塞,直到发生一些paint事件(由我定义并在另外一个线程中调度)之前发生。

但是我不知道阻塞功能如何工作。当然,我可以创建一个 sleep()循环,但这样的循环有固定的FPS会占用资源,即使没有发生任何事情(我已经阐述了这个主题此处)。在其他方面,它不显示数据即时。这对于GUI应用来说不是很好。

I have a problem with rendering thread - i need a blocking function that will, for example, block until some paint event (defined by me and dispatched in one of other two threads) happens.
But I don't know how blocking functions work. I can, of course, create an sleep() loop, but such loop has fixed FPS takes resources even if nothing happens (I've already elaborated on that topic here). On the oher side, it does not display data immediatelly. This is not good for GUI application.

推荐答案

如果您使用C ++ 11,可以使用 std :: condition_variable
std :: mutex

If you're using C++11, you can use std::condition_variable and std::mutex:

void
waitForEvent()
{
    std::unique_lock<std::mutex> lock( myMutex );
    while ( ! externalCondition ) {
        myConditionVariable.wait( lock );
    }
}

触发事件:

void
setEvent()
{
    std::unique_lock<std::mutex> lock( myMutex );
    setExternalCondition();
}

另一方面,您提到一个GUI和一个渲染器。你
不能在GUI线程中等待外部条件。如果
您需要在GUI线程中进行渲染,则必须
了解如何在GUI管理器中创建GUI事件,并发布
GUI事件。

On the other hand, you mention a GUI and a renderer. You cannot wait on an external condition in the GUI thread. If you need to be in the GUI thread for rendering, you'll have to find out how to create a GUI event in your GUI manager, and post the GUI event.

这篇关于C ++中的自定义阻止功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆