【问题标题】:Which protection method to use (mutex , readwritelock ..) on thread inner function在线程内部函数上使用哪种保护方法(mutex,readwritelock ..)
【发布时间】:2012-02-01 07:55:56
【问题描述】:

我有一个线程从 Web 服务轮询数据,然后将其发送到不同的类来处理数据。该数据的处理可能需要很长时间,有时超过调用线程内轮询函数的计时器间隔。
我想保护这个轮询功能,就是在处理数据的过程中,不要进入这个功能。

我的流程是这样的

workerThread -> start timer -> that invoking the polling method ->
the polling method gets the data and send it to processing  > mean while this polling function can be called again .

【问题讨论】:

    标签: c++ qt qthread


    【解决方案1】:

    如果轮询函数的执行时间比轮询计时器的执行时间长,则可以尝试锁定互斥体

    void pollingFunction() {
    
        bool isLocked = mutex.tryLock(3000); //timeout if you want
        if(isLocked) 
        {
           //process the data
        }
        else 
        {
          return;
        }
    
        mutex.unlock();
    } 
    

    【讨论】:

      【解决方案2】:

      我假设您至少使用了 2 个线程。一个由定时器触发,另一个处理轮询数据。因此监视器对象模式适用于它,您需要为轮询数据定义一个队列并定义 2 个条件变量(不满,不空)。如果未满,则可以开始轮询,然后将数据放入队列。如果它不为空,则处理可以检索数据并处理它。

      【讨论】:

        猜你喜欢
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-21
        • 2011-01-23
        • 2021-06-11
        • 2013-03-11
        • 1970-01-01
        相关资源
        最近更新 更多