在线程内部函数上使用哪种保护方法(互斥,读写锁.)

Which protection method to use (mutex , readwritelock ..) on thread inner function

本文关键字:互斥 方法 读写 写锁 保护 内部函数 线程      更新时间:2023-10-16

我有一个线程,它从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 .

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

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

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