3

我有一个线程阻塞,直到从系统资源(如 USB 设备)接收到数据。我之所以选择这个模型,是因为数据量可能会有所不同,并且随时可能收到数据。退出应用程序后,我收到消息“<strong>QThread: Destroyed while thread is still running”。我应该如何关闭这些线程?

我查看了其他问题/解决方案,例如:

第一个解决方案涉及使用标志(包含在我的代码中)但是我的线程永远不会到达标志检查。第二个解决方案使用 QWaitCondition 但似乎与第一个解决方案相同。

我已经包含了下面代码的精简版本。系统调用 WaitForSingleObject() 是我实际使用的 (GetOverlappedResult()) 的替代品。

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include <QObject>
#include <QThread>
#include <QReadWriteLock>
#include <QDebug>

#ifdef Q_OS_WIN
    #include <windows.h>
#endif // Q_OS_WIN

#ifdef Q_OS_LINUX
    #include <unistd.h>
#endif // Q_OS_LINUX

////////////////////////////////////////////////
//
//  Worker Object
//
////////////////////////////////////////////////
class Worker : public QObject {
    Q_OBJECT

public:
    QReadWriteLock lock;
    bool running;

public slots:
    void loop() {
        qDebug() << "entering the loop";
        bool _running;
        forever {

            lock.lockForRead();
            _running = running;
            lock.unlock();

            if (!_running) return;

            qDebug() << "loop iteration";

            #ifdef Q_OS_WIN
                HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL);
                WaitForSingleObject(event, INFINITE);
            #endif // Q_OS_WIN

            #ifdef Q_OS_LINUX
                read(0, 0, 1);
            #endif // Q_OS_LINUX
        }
    }
};

////////////////////////////////////////////////
//
//  Controller
//
////////////////////////////////////////////////
class Controller {
public:
    Controller() {
        myWorker.connect(&myThread, SIGNAL(started()), &myWorker, SLOT(loop()));
        myWorker.moveToThread(&myThread);
        myThread.start();
    }

    ~Controller() {
        // Safely close threads

        myWorker.lock.lockForWrite();
        myWorker.running = false;
        myWorker.lock.unlock();

        myThread.quit();

        //myThread.wait();
        //myThread.exit();
        //myThread.terminate();
    }

private:
    QThread myThread;
    Worker myWorker;
};

#endif // CONTROLLER_H
4

1 回答 1

-1

对于 Linux:

使用 pthread_kill() 向线程发送信号会中断 read(),失败代码为 EINTR。sigaction() 用于注册信号,抛出的信号是SIGUSR1。

// Global scope
void nothing(int signum) {}

...

// Within the start of the thread
pthread_t myThreadID = pthread_self(); // Get the thread ID
struct sigaction action;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
action.sa_handler = nothing;
sigaction(SIGUSR1, &action, NULL);

...

// When it's time to close the thread
pthread_kill(myThreadID, SIGUSR1);

对于 Windows:

使用 SetEvent() 向 OVERLAPPED 的 hEvent 发送信号用于解除对 GetOverlappedResult() 的阻塞。

// Store a reference to the event
HANDLE myEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

...

// Within the start of the thread
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = myEvent;

...

// When it's time to close the thread
SetEvent(myEvent);
于 2012-11-30T12:14:23.730 回答