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

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

问题描述

我正在创建基于 while(true)和阻塞函数的三个线程的应用程序模型。


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

  2. 锁定的线程 - 等待来自服务器的数据阻止套接字。


  3. $ b

    我有一个问题,渲染线程 - 我需要一个阻塞函数,例如阻塞直到某些绘制事件(由我定义并且在其他两个线程之一中分派)发生。

    但是我不知道阻塞函数是如何工作的。我可以,当然,创建一个 sleep()循环,但这样的循环有固定的FPS需要资源,即使没有发生任何事情(我已经阐述了这个主题这里)。在其他方面,它不立即显示数据。

    解决方案

    如果你使用C ++ 11,你可以使用 std :: condition_variable
    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事件。


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

    1. Event thread - waits for user input, blocked by SDL_WaitEvent
    2. Socked thread - waits for data from server, blocked by blocking socket.
    3. Render thread - renders data from buffer, not blocked.

    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.

    解决方案

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

    To trigger the event:

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

    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天全站免登陆