首页 > 解决方案 > 寻找在我的应用程序中使用关键部分的潜在危险,我在 SO 中阅读了一些答案,这给了我灵感

问题描述

我写了下面的代码,背后的道理很简单;

  1. 线程一直运行,直到它在应用程序关闭时终止。
  2. Add(request1, request2, host, port) 用于将元素添加到 std::queue
  3. 确保分派请求之间存在时间延迟
  4. 检查队列的大小,如果大小> 0,则执行该工作
  5. DispatchRequest 到创建单个线程的 TThreadComponent。
  6. 移除(弹出)队列元素

我已经运行了代码,它似乎运行良好并且符合预期。

该线程运行时,主应用程序保持响应。

我的问题是,任何人都可以看到我应该注意的潜在问题。

在没有更具体的代码可以利用这个线程的情况下,我希望有足够的线程让经验丰富的人能够识别潜在的危险并提供改进提示。

干杯

void __fastcall TSentinal::Execute()
{
//---- Place thread code here -------------------
//
//    using std::queue to request reading a modbus
//    device via a thread component, component
//    creates the reading thread which terminates
//      after read,
//-----------------------------------------------
if (!InitializeCriticalSectionAndSpinCount(&gateKeeper, 0x00000400) )
    return;

Priority = tpNormal;
FreeOnTerminate = true;
span.start = clock();

while(!Terminated)
    {
    //---------------------------------------------------
    //  wait for millisec_delay between DispatchRequests
    //  to ensure time for other thread to complete its
//  task...
    //---------------------------------------------------
    millisec_delay = 500;

    while(!span.dispatch(millisec_delay))
        continue;

    if((size_t)q.size() > 0)
        {
        span.start = clock();

        EnterCriticalSection(&gateKeeper);
        //-----------------------------------------------
        //  ensure that request is completed before
        //  continuing,
        //
        //  DispatchRequest() creates thread to read modbus
        //  device via serial server, on completion, thread
        //  is terminated,
        //-----------------------------------------------
        FTc->DispatchRequest(false, q.c[0]);
        //-----------------------------------------------
        //  remove from queue
        //-----------------------------------------------
        q.pop();

        LeaveCriticalSection(&gateKeeper);
        }
    }
DeleteCriticalSection(&gateKeeper);

}

标签: c++c++builder

解决方案


推荐阅读