这种方式是以重写run()函数,将需要在另一个线程中执行的操作在run()中进行实现。一般会在run()中创建一个while循环,使用条件去控制循环中的工作,这样的方式适用于需要长期单独的线程中执行的操作,当想要结束这个线程的时候,修改条件跳出循环结束run()函数的其他的操作即可。同时QThread发出finished()信号。

    1. void CheckInputThread::run()
    2. {
    3. while (!stopped)
    4. {
    5. if (testing)
    6. {
    7. if(motion.GetIfInput() != status )
    8. {
    9. mutex.lock();
    10. if (status)
    11. {
    12. //从有到无:下料
    13. reload = 0;
    14. }else{
    15. //从无到有:上料
    16. reload = 1;
    17. }
    18. emit loadStatus(reload);
    19. status = motion.GetIfInput();
    20. mutex.unlock();
    21. }
    22. }
    23. msleep(50);
    24. }
    25. }
    26. void CheckInputThread::End()
    27. {
    28. stopped = true;
    29. wait();
    30. }
    31. void CheckInputThread::Begin()
    32. {
    33. stopped = false;
    34. start(); //当start()函数调用后run()就会开始执行,如果没有while进行循环,则会执行完就退出,需要重新start()才会再次执行
    35. }
    36. void CheckInputThread::StartWork()
    37. {
    38. testing = true;
    39. mutex.lock();
    40. status = motion.GetIfInput();
    41. reload = status ? 2 : 3;
    42. emit loadStatus(reload);
    43. mutex.unlock();
    44. }
    45. void CheckInputThread::StopWork()
    46. {
    47. testing = false;
    48. }

    分析:https://www.codenong.com/60939559/