QThread的多个实例可以引用相同的OS线程吗?

时间:2016-11-17 01:56:35

标签: c++ multithreading qt qt5 qthread

我使用QThread作为线程管理器,我想知道是否可以实现多个QThread对象,这些对象都管理同一个线程?

1 个答案:

答案 0 :(得分:1)

不,当然。

单个线程只能由1个QThread管理,因为它将在void QThread::start(Priority)内部创建,现在可以将线程设置为QThread

来自qthread_unix.cpp

int code = pthread_create(&threadId, &attr, QThreadPrivate::start, this);

pthread_create将开始一个新主题。

来自qthread_win.cpp

#if defined(Q_CC_MSVC) && !defined(_DLL) // && !defined(Q_OS_WINRT)
#  ifdef Q_OS_WINRT
    // If you wish to accept the memory leaks, uncomment the part above.
    // See:
    //  https://support.microsoft.com/en-us/kb/104641
    //  https://msdn.microsoft.com/en-us/library/kdzttdcb.aspx
#    error "Microsoft documentation says this combination leaks memory every time a thread is started. " \
    "Please change your build back to -MD/-MDd or, if you understand this issue and want to continue, " \
    "edit this source file."
#  endif
    // MSVC -MT or -MTd build
    d->handle = (Qt::HANDLE) _beginthreadex(NULL, d->stackSize, QThreadPrivate::start,
                                            this, CREATE_SUSPENDED, &(d->id));
#else
    // MSVC -MD or -MDd or MinGW build
    d->handle = (Qt::HANDLE) CreateThread(NULL, d->stackSize, (LPTHREAD_START_ROUTINE)QThreadPrivate::start,
                                            this, CREATE_SUSPENDED, reinterpret_cast<LPDWORD>(&d->id));
#endif // Q_OS_WINRT

当然,CreateThread_beginthreadex都会创建一个新主题。