Qt 4.8
Public Types | Public Slots | Signals | Public Functions | Static Public Functions | Protected Functions | Static Protected Functions | Static Private Functions | Friends | List of all members
QThread Class Reference

The QThread class provides a platform-independent way to manage threads. More...

#include <qthread.h>

Inheritance diagram for QThread:
QObject QAdoptedThread QBBScreenEventThread QDeclarativePixmapReader QDeclarativeWorkerScriptEngine QDeclarativeXmlQueryEngine QDirectFbInput QDnotifySignalThread QFileInfoGatherer QFileSystemWatcherEngine QIntKeyboardListenThread QIntMouseListenThread QNlaThread QProcessManager QScanThread QThreadPoolThread QWindowsFileSystemWatcherEngineThread QWindowsPipeWriter SelectWorker

Public Types

enum  Priority {
  IdlePriority, LowestPriority, LowPriority, NormalPriority,
  HighPriority, HighestPriority, TimeCriticalPriority, InheritPriority
}
 This enum type indicates how the operating system should schedule newly created threads. More...
 

Public Slots

void quit ()
 Tells the thread's event loop to exit with return code 0 (success). More...
 
void start (Priority=InheritPriority)
 Begins execution of the thread by calling run(). More...
 
void terminate ()
 Terminates the execution of the thread. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void finished ()
 This signal is emitted when the thread has finished executing. More...
 
void started ()
 This signal is emitted when the thread starts executing. More...
 
void terminated ()
 This signal is emitted when the thread is terminated. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

void exit (int retcode=0)
 Tells the thread's event loop to exit with a return code. More...
 
bool isFinished () const
 Returns true if the thread is finished; otherwise returns false. More...
 
bool isRunning () const
 Returns true if the thread is running; otherwise returns false. More...
 
Priority priority () const
 Returns the priority for a running thread. More...
 
 QThread (QObject *parent=0)
 Constructs a new QThread to manage a new thread. More...
 
void setPriority (Priority priority)
 This function sets the priority for a running thread. More...
 
void setStackSize (uint stackSize)
 Sets the maximum stack size for the thread to stackSize. More...
 
uint stackSize () const
 Returns the maximum stack size for the thread (if set with setStackSize()); otherwise returns zero. More...
 
bool wait (unsigned long time=ULONG_MAX)
 Blocks the thread until either of these conditions is met: More...
 
 ~QThread ()
 Destroys the QThread. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static QThreadcurrentThread ()
 Returns a pointer to a QThread which manages the currently executing thread. More...
 
static Qt::HANDLE currentThreadId ()
 Returns the thread handle of the currently executing thread. More...
 
static int idealThreadCount ()
 Returns the ideal number of threads that can be run on the system. More...
 
static void yieldCurrentThread ()
 Yields execution of the current thread to another runnable thread, if any. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Functions

int exec ()
 Enters the event loop and waits until exit() is called, returning the value that was passed to exit(). More...
 
 QThread (QThreadPrivate &dd, QObject *parent=0)
 
virtual void run ()
 The starting point for the thread. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Static Protected Functions

static void msleep (unsigned long)
 Forces the current thread to sleep for msecs milliseconds. More...
 
static void setTerminationEnabled (bool enabled=true)
 Enables or disables termination of the current thread based on the enabled parameter. More...
 
static void sleep (unsigned long)
 Forces the current thread to sleep for secs seconds. More...
 
static void usleep (unsigned long)
 Forces the current thread to sleep for usecs microseconds. More...
 

Static Private Functions

static void cleanup ()
 Cleans up the QThread system. More...
 
static void initialize ()
 

Friends

class QCoreApplication
 
class QThreadData
 

Additional Inherited Members

- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QThread class provides a platform-independent way to manage threads.

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

You can use worker objects by moving them to the thread using QObject::moveToThread().

class Worker : public QObject
{
QThread workerThread;
public slots:
void doWork(const QString &parameter) {
// ...
emit resultReady(result);
}
void resultReady(const QString &result);
};
class Controller : public QObject
{
QThread workerThread;
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(this, SIGNAL(operate(QString)), worker, SLOT(doWork(QString)));
connect(worker, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString)));
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
public slots:
void handleResults(const QString &);
void operate(const QString &);
};

The code inside the Worker's slot would then execute in a separate thread. However, you are free to connect the Worker's slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.

Another way to make code run in a separate thread, is to subclass QThread and reimplement run(). For example:

class WorkerThread : public QThread
{
void run() {
QString result;
/* expensive or blocking operation */
emit resultReady(result);
}
void resultReady(const QString &s);
};
void MyObject::startWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread(this);
connect(workerThread, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString)));
connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
workerThread->start();
}

In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.

When subclassing QThread, keep in mind that the constructor executes in the old thread while run() executes in the new thread. If a member variable is accessed from both functions, then the variable is accessed from two different threads. Check that it is safe to do so.

Note
Care must be taken when interacting with objects across different threads. See Synchronizing Threads for details.

Managing threads

QThread will notifiy you via a signal when the thread is started(), finished(), and terminated(), or you can use isFinished() and isRunning() to query the state of the thread.

You can stop the thread by calling exit() or quit(). In extreme cases, you may want to forcibly terminate() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for terminate() and setTerminationEnabled() for detailed information.

From Qt 4.8 onwards, it is possible to deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater().

Use wait() to block the calling thread, until the other thread has finished execution (or until a specified time has passed).

The static functions currentThreadId() and currentThread() return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a QThread pointer.

To choose the name that your thread will be given (as identified by the command ps -L on Linux, for example), you can call setObjectName() before starting the thread. If you don't call setObjectName(), the name given to your thread will be the class name of the runtime type of your thread object (for example, "RenderThread" in the case of the Mandelbrot Example, as that is the name of the QThread subclass). Note that this is currently not available with release builds on Windows.

QThread also provides static, platform independent sleep functions: sleep(), msleep(), and usleep() allow full second, millisecond, and microsecond resolution respectively.

Note
wait() and the sleep() functions should be unnecessary in general, since Qt is an event-driven framework. Instead of wait(), consider listening for the finished() signal. Instead of the sleep() functions, consider using QTimer.
See also
{Thread Support in Qt}, QThreadStorage, {Synchronizing Threads} {Mandelbrot Example}, {Semaphores Example}, {Wait Conditions Example}

Definition at line 59 of file qthread.h.

Enumerations

◆ Priority

This enum type indicates how the operating system should schedule newly created threads.

  • IdlePriority scheduled only when no other threads are running.
  • LowestPriority scheduled less often than LowPriority.
  • LowPriority scheduled less often than NormalPriority.
  • NormalPriority the default priority of the operating system.
  • HighPriority scheduled more often than NormalPriority.
  • HighestPriority scheduled more often than HighPriority.
  • TimeCriticalPriority scheduled as often as possible.
  • InheritPriority use the same priority as the creating thread. This is the default.
Enumerator
IdlePriority 
LowestPriority 
LowPriority 
NormalPriority 
HighPriority 
HighestPriority 
TimeCriticalPriority 
InheritPriority 

Definition at line 70 of file qthread.h.

Constructors and Destructors

◆ QThread() [1/2]

QThread::QThread ( QObject parent = 0)
explicit

Constructs a new QThread to manage a new thread.

The parent takes ownership of the QThread. The thread does not begin executing until start() is called.

See also
start()

Definition at line 433 of file qthread.cpp.

Referenced by priority().

434  : QObject(*(new QThreadPrivate), parent)
435 {
436  Q_D(QThread);
437  // fprintf(stderr, "QThreadData %p created for thread %p\n", d->data, this);
438  d->data->thread = this;
439 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ ~QThread()

QThread::~QThread ( )

Destroys the QThread.

Note that deleting a QThread object will not stop the execution of the thread it manages. Deleting a running QThread (i.e. isFinished() returns false) will probably result in a program crash. Wait for the finished() signal before deleting the QThread.

Definition at line 460 of file qthread.cpp.

461 {
462  Q_D(QThread);
463  {
464  QMutexLocker locker(&d->mutex);
465  if (d->isInFinish) {
466  locker.unlock();
467  wait();
468  locker.relock();
469  }
470  if (d->running && !d->finished && !d->data->isAdopted)
471  qWarning("QThread: Destroyed while thread is still running");
472 
473  d->data->thread = 0;
474  }
475 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
bool wait(unsigned long time=ULONG_MAX)
Blocks the thread until either of these conditions is met:
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ QThread() [2/2]

QThread::QThread ( QThreadPrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 443 of file qthread.cpp.

444  : QObject(dd, parent)
445 {
446  Q_D(QThread);
447  // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
448  d->data->thread = this;
449 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

Functions

◆ cleanup()

void QThread::cleanup ( )
staticprivate

Cleans up the QThread system.

Warning
This function is not part of the public interface.

Definition at line 661 of file qthread.cpp.

Referenced by QCoreApplication::~QCoreApplication().

662 {
664 }
Q_CORE_EXPORT QMutexPool * qt_global_mutexpool
Definition: qmutexpool.cpp:51

◆ currentThread()

QThread * QThread::currentThread ( )
static

Returns a pointer to a QThread which manages the currently executing thread.

Definition at line 419 of file qthread.cpp.

Referenced by QDBusConnectionPrivate::activateCall(), QEventDispatcherUNIX::activateTimers(), QTextHtmlParserNode::applyBackgroundImage(), QDBusAbstractInterface::callWithArgumentList(), QCoreApplicationPrivate::checkReceiverThread(), connManager(), QDBusConnectionPrivate::deleteYourself(), QDBusConnectionPrivate::deliverCall(), QNetworkSession::disconnectNotify(), QTextImageHandler::drawObject(), elapsed(), QThreadStorageData::finish(), QDBusConnectionPrivate::handleObjectCall(), QEventDispatcherQPAPrivate::hasIntegration(), huntAndEmit(), QGLSignalProxy::instance(), QTextImageHandler::intrinsicSize(), QMetaMethod::invoke(), QRawFontPrivate::isValid(), jump(), QRawFont::loadFromData(), QTextDocument::loadResource(), QFontDatabase::loadXlfd(), QHostInfo::lookupHost(), QBBScreen::newWindowCreated(), QApplication::notify(), operator<<(), priority(), QStateMachinePrivate::processEvents(), QCoreApplicationPrivate::QCoreApplicationPrivate(), qDBusAddTimeout(), qDBusAddWatch(), qDBusIntrospectObject(), qDBusPropertyGet(), qDBusPropertyGetAll(), qDBusPropertySet(), qDBusRemoveTimeout(), qDBusRemoveWatch(), qDBusToggleWatch(), QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(), QFontEngineX11FT::QFontEngineX11FT(), QGLEngineSharedShaders::QGLEngineSharedShaders(), qt_grab_cursor(), qt_painter_thread_test(), qt_pixmap_thread_test(), qt_set_current_thread_to_main_thread(), qt_win_display_dc(), QEventDispatcherWin32::registerEventNotifier(), QEventDispatcherGlib::registerSocketNotifier(), QEventDispatcherWin32::registerSocketNotifier(), QEventDispatcherMac::registerSocketNotifier(), QEventDispatcherUNIX::registerSocketNotifier(), QEventDispatcherGlib::registerTimer(), QEventDispatcherWin32::registerTimer(), QEventDispatcherMac::registerTimer(), QEventDispatcherUNIX::registerTimer(), QDBusAdaptorConnector::relaySlot(), QSocks5BindStore::retrieve(), QEventDispatcherQPAPrivate::runEventLoopIntegration(), QPlatformGLContextPrivate::setCurrentContext(), QEventDispatcherUNIX::setSocketNotifierPending(), QMacPrintEnginePrivate::shouldSuppressStatus(), QEventDispatcherWin32::unregisterEventNotifier(), QEventDispatcherGlib::unregisterSocketNotifier(), QEventDispatcherWin32::unregisterSocketNotifier(), QEventDispatcherMac::unregisterSocketNotifier(), QEventDispatcherUNIX::unregisterSocketNotifier(), QEventDispatcherGlib::unregisterTimer(), QEventDispatcherWin32::unregisterTimer(), QEventDispatcherMac::unregisterTimer(), QEventDispatcherUNIX::unregisterTimer(), QEventDispatcherGlib::unregisterTimers(), QEventDispatcherWin32::unregisterTimers(), QEventDispatcherMac::unregisterTimers(), QEventDispatcherUNIX::unregisterTimers(), QBBScreen::windowClosed(), QDBusConnectionPrivate::~QDBusConnectionPrivate(), and QGLEngineSharedShaders::~QGLEngineSharedShaders().

420 {
422  Q_ASSERT(data != 0);
423  return data->thread;
424 }
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
static const char * data(const QByteArray &arr)
static QThreadData * current()
QThread * thread
Definition: qthread_p.h:260

◆ currentThreadId()

Qt::HANDLE QThread::currentThreadId ( )
static

Returns the thread handle of the currently executing thread.

Warning
The handle returned by this function is used for internal purposes and should not be used in any application code.
On Windows, the returned value is a pseudo-handle for the current thread. It can't be used for numerical comparison. i.e., this function returns the DWORD (Windows-Thread ID) returned by the Win32 function getCurrentThreadId(), not the HANDLE (Windows-Thread HANDLE) returned by the Win32 function getCurrentThread().

Definition at line 400 of file qthread_unix.cpp.

Referenced by QHttpThreadDelegate::abortRequest(), QMetaObject::activate(), QGLContext::choosePixelFormat(), QThreadPrivate::finish(), QHttpThreadDelegate::finishedSlot(), QHttpThreadDelegate::finishedWithErrorSlot(), QHttpThreadDelegate::headerChangedSlot(), id_function(), QMutex::lock(), QReadWriteLock::lockForRead(), QReadWriteLock::lockForWrite(), QCoreApplicationPrivate::QCoreApplicationPrivate(), QEventDispatcherUNIXPrivate::QEventDispatcherUNIXPrivate(), QHttpThreadDelegate::startRequest(), QHttpThreadDelegate::startRequestSynchronously(), QHttpThreadDelegate::synchronousAuthenticationRequiredSlot(), QHttpThreadDelegate::synchronousFinishedSlot(), QHttpThreadDelegate::synchronousFinishedWithErrorSlot(), QHttpThreadDelegate::synchronousHeaderChangedSlot(), QHttpThreadDelegate::synchronousProxyAuthenticationRequiredSlot(), QMutex::tryLock(), QReadWriteLock::tryLockForRead(), QReadWriteLock::tryLockForWrite(), and QReadWriteLock::unlock().

401 {
402  // requires a C cast here otherwise we run into trouble on AIX
403  return (Qt::HANDLE)pthread_self();
404 }
void * HANDLE
Definition: qnamespace.h:1671

◆ exec()

int QThread::exec ( )
protected

Enters the event loop and waits until exit() is called, returning the value that was passed to exit().

The value returned is 0 if exit() is called via quit().

This function is meant to be called from within run(). It is necessary to call this function to start event handling.

See also
quit(), exit()

Definition at line 551 of file qthread.cpp.

Referenced by QDeclarativeXmlQueryEngine::run().

552 {
553  Q_D(QThread);
554  QMutexLocker locker(&d->mutex);
555  d->data->quitNow = false;
556  if (d->exited) {
557  d->exited = false;
558  return d->returnCode;
559  }
560  locker.unlock();
561 
562  QEventLoop eventLoop;
563  int returnCode = eventLoop.exec();
564 
565  locker.relock();
566  d->exited = false;
567  d->returnCode = -1;
568  return returnCode;
569 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QEventLoop class provides a means of entering and leaving an event loop.
Definition: qeventloop.h:55
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59
int exec(ProcessEventsFlags flags=AllEvents)
Enters the main event loop and waits until exit() is called.
Definition: qeventloop.cpp:181

◆ exit()

void QThread::exit ( int  returnCode = 0)

Tells the thread's event loop to exit with a return code.

After calling this function, the thread leaves the event loop and returns from the call to QEventLoop::exec(). The QEventLoop::exec() function returns returnCode.

By convention, a returnCode of 0 means success, any non-zero value indicates an error.

Note that unlike the C library function of the same name, this function does return to the caller – it is event processing that stops.

No QEventLoops will be started anymore in this thread until QThread::exec() has been called again. If the eventloop in QThread::exec() is not running then the next call to QThread::exec() will also return immediately.

See also
quit() QEventLoop

Definition at line 592 of file qthread.cpp.

Referenced by quit(), QIntMouseListenThread::run(), and QIntKeyboardListenThread::run().

593 {
594  Q_D(QThread);
595  QMutexLocker locker(&d->mutex);
596  d->exited = true;
597  d->returnCode = returnCode;
598  d->data->quitNow = true;
599  for (int i = 0; i < d->data->eventLoops.size(); ++i) {
600  QEventLoop *eventLoop = d->data->eventLoops.at(i);
601  eventLoop->exit(returnCode);
602  }
603 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QEventLoop class provides a means of entering and leaving an event loop.
Definition: qeventloop.h:55
void exit(int returnCode=0)
Tells the event loop to exit with a return code.
Definition: qeventloop.cpp:288
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ finished

bool QThread::finished ( )
signal

This signal is emitted when the thread has finished executing.

Use isFinished() instead.

See also
started(), terminated()

Referenced by QThreadData::current(), QThreadPrivate::finish(), and QAdoptedThread::QAdoptedThread().

◆ idealThreadCount()

int QThread::idealThreadCount ( )
static

Returns the ideal number of threads that can be run on the system.

This is done querying the number of processor cores, both real and logical, in the system. This function returns -1 if the number of processor cores could not be detected.

Definition at line 411 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and QMutex::lockInternal().

412 {
413  int cores = -1;
414 
415 #if defined(Q_OS_MAC) && !defined(Q_WS_QPA)
416  // Mac OS X
417  cores = MPProcessorsScheduled();
418 #elif defined(Q_OS_HPUX)
419  // HP-UX
420  struct pst_dynamic psd;
421  if (pstat_getdynamic(&psd, sizeof(psd), 1, 0) == -1) {
422  perror("pstat_getdynamic");
423  cores = -1;
424  } else {
425  cores = (int)psd.psd_proc_cnt;
426  }
427 #elif defined(Q_OS_BSD4)
428  // FreeBSD, OpenBSD, NetBSD, BSD/OS
429  size_t len = sizeof(cores);
430  int mib[2];
431  mib[0] = CTL_HW;
432  mib[1] = HW_NCPU;
433  if (sysctl(mib, 2, &cores, &len, NULL, 0) != 0) {
434  perror("sysctl");
435  cores = -1;
436  }
437 #elif defined(Q_OS_IRIX)
438  // IRIX
439  cores = (int)sysconf(_SC_NPROC_ONLN);
440 #elif defined(Q_OS_INTEGRITY)
441 #if (__INTEGRITY_MAJOR_VERSION >= 10)
442  // Integrity V10+ does support multicore CPUs
443  Value processorCount;
444  if (GetProcessorCount(CurrentTask(), &processorCount) == 0)
445  cores = processorCount;
446  else
447 #endif
448  cores = 1;
449 #elif defined(Q_OS_VXWORKS)
450  // VxWorks
451 # if defined(QT_VXWORKS_HAS_CPUSET)
452  cpuset_t cpus = vxCpuEnabledGet();
453  cores = 0;
454 
455  // 128 cores should be enough for everyone ;)
456  for (int i = 0; i < 128 && !CPUSET_ISZERO(cpus); ++i) {
457  if (CPUSET_ISSET(cpus, i)) {
458  CPUSET_CLR(cpus, i);
459  cores++;
460  }
461  }
462 # else
463  // as of aug 2008 VxWorks < 6.6 only supports one single core CPU
464  cores = 1;
465 # endif
466 #else
467  // the rest: Linux, Solaris, AIX, Tru64
468  cores = (int)sysconf(_SC_NPROCESSORS_ONLN);
469 #endif
470 
471  return cores;
472 }
int mib

◆ initialize()

void QThread::initialize ( )
staticprivate

Definition at line 643 of file qthread.cpp.

Referenced by QCoreApplication::init().

644 {
646  return;
648 
649 #if defined (Q_OS_WIN)
650  qt_create_tls();
651 #endif
652 }
static QMutexPool * instance()
Returns the global QMutexPool instance.
Definition: qmutexpool.cpp:124
Q_CORE_EXPORT QMutexPool * qt_global_mutexpool
Definition: qmutexpool.cpp:51
void qt_create_tls()
Initializes the QThread system.
Definition: qthread_win.cpp:78

◆ isFinished()

bool QThread::isFinished ( ) const

Returns true if the thread is finished; otherwise returns false.

See also
isRunning()

Definition at line 482 of file qthread.cpp.

483 {
484  Q_D(const QThread);
485  QMutexLocker locker(&d->mutex);
486  return d->finished || d->isInFinish;
487 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ isRunning()

bool QThread::isRunning ( ) const

Returns true if the thread is running; otherwise returns false.

See also
isFinished()

Definition at line 494 of file qthread.cpp.

Referenced by QKqueueFileSystemWatcherEngine::addPaths(), QWindowsPipeWriter::write(), and QDnotifySignalThread::~QDnotifySignalThread().

495 {
496  Q_D(const QThread);
497  QMutexLocker locker(&d->mutex);
498 #ifdef Q_OS_SYMBIAN
499  // app shutdown on Symbian can terminate threads and invalidate their stacks without notification,
500  // check the thread is still alive.
501  if (d->data->symbian_thread_handle.Handle() && d->data->symbian_thread_handle.ExitType() != EExitPending)
502  return false;
503 #endif
504  return d->running && !d->isInFinish;
505 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ msleep()

void QThread::msleep ( unsigned long  msecs)
staticprotected

Forces the current thread to sleep for msecs milliseconds.

See also
sleep(), usleep()

Definition at line 509 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and QWindowsPipeWriter::run().

510 {
511  struct timeval tv;
512  gettimeofday(&tv, 0);
513  struct timespec ti;
514 
515  ti.tv_nsec = (tv.tv_usec + (msecs % 1000) * 1000) * 1000;
516  ti.tv_sec = tv.tv_sec + (msecs / 1000) + (ti.tv_nsec / 1000000000);
517  ti.tv_nsec %= 1000000000;
518  thread_sleep(&ti);
519 }
static void thread_sleep(struct timespec *ti)

◆ priority()

QThread::Priority QThread::priority ( ) const

Returns the priority for a running thread.

Since
4.1

If the thread is not running, this function returns InheritPriority.

See also
Priority setPriority() start()

Definition at line 718 of file qthread.cpp.

Referenced by QThreadPrivate::start().

719 {
720  Q_D(const QThread);
721  QMutexLocker locker(&d->mutex);
722 
723  // mask off the high bits that are used for flags
724  return Priority(d->priority & 0xffff);
725 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Priority
This enum type indicates how the operating system should schedule newly created threads.
Definition: qthread.h:70
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ quit

void QThread::quit ( )
slot

Tells the thread's event loop to exit with return code 0 (success).

Equivalent to calling QThread::exit(0).

This function does nothing if the thread does not have an event loop.

See also
exit() QEventLoop

Definition at line 614 of file qthread.cpp.

Referenced by QNetworkAccessHttpBackend::postRequest(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::QDeclarativeXmlQueryEngine(), QDnotifySignalThread::readFromDnotify(), QInotifyFileSystemWatcherEngine::stop(), QPollingFileSystemWatcherEngine::stop(), QDnotifySignalThread::~QDnotifySignalThread(), and QNetworkConfigurationManagerPrivate::~QNetworkConfigurationManagerPrivate().

615 { exit(); }
void exit(int retcode=0)
Tells the thread&#39;s event loop to exit with a return code.
Definition: qthread.cpp:592

◆ run()

void QThread::run ( void  )
protectedvirtual

The starting point for the thread.

After calling start(), the newly created thread calls this function. The default implementation simply calls exec().

You can reimplement this function to facilitate advanced thread management. Returning from this method will end the execution of the thread.

See also
start() wait()

Reimplemented in QAdoptedThread, QNlaThread, QDeclarativeXmlQueryEngine, QProcessManager, QFileInfoGatherer, QIntKeyboardListenThread, QDeclarativePixmapReader, QWindowsFileSystemWatcherEngineThread, QWindowsPipeWriter, QScanThread, QPollingFileSystemWatcherEngine, QFSEventsFileSystemWatcherEngine, SelectWorker, QDnotifySignalThread, QIntMouseListenThread, QKqueueFileSystemWatcherEngine, QDeclarativeWorkerScriptEngine, QDnotifyFileSystemWatcherEngine, QInotifyFileSystemWatcherEngine, QThreadPoolThread, QDirectFbInput, and QBBScreenEventThread.

Definition at line 628 of file qthread.cpp.

Referenced by qt_adopted_thread_watcher_function(), and QThreadPrivate::start().

629 {
630  (void) exec();
631 }
int exec()
Enters the event loop and waits until exit() is called, returning the value that was passed to exit()...
Definition: qthread.cpp:551

◆ setPriority()

void QThread::setPriority ( Priority  priority)

This function sets the priority for a running thread.

Since
4.1

If the thread is not running, this function does nothing and returns immediately. Use start() to start a thread with a specific priority.

The priority argument can be any value in the QThread::Priority enum except for InheritPriorty.

The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler for more details).

See also
Priority priority() start()

Definition at line 738 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and QThreadPrivate::start().

739 {
740  Q_D(QThread);
741  QMutexLocker locker(&d->mutex);
742  if (!d->running) {
743  qWarning("QThread::setPriority: Cannot set priority, thread is not running");
744  return;
745  }
746 
747  d->priority = priority;
748 
749  // copied from start() with a few modifications:
750 
751 #ifdef QT_HAS_THREAD_PRIORITY_SCHEDULING
752  int sched_policy;
753  sched_param param;
754 
755  if (pthread_getschedparam(d->thread_id, &sched_policy, &param) != 0) {
756  // failed to get the scheduling policy, don't bother setting
757  // the priority
758  qWarning("QThread::setPriority: Cannot get scheduler parameters");
759  return;
760  }
761 
762  int prio;
763  if (!calculateUnixPriority(priority, &sched_policy, &prio)) {
764  // failed to get the scheduling parameters, don't
765  // bother setting the priority
766  qWarning("QThread::setPriority: Cannot determine scheduler priority range");
767  return;
768  }
769 
770  param.sched_priority = prio;
771  int status = pthread_setschedparam(d->thread_id, sched_policy, &param);
772 
773 # ifdef SCHED_IDLE
774  // were we trying to set to idle priority and failed?
775  if (status == -1 && sched_policy == SCHED_IDLE && errno == EINVAL) {
776  // reset to lowest priority possible
777  pthread_getschedparam(d->thread_id, &sched_policy, &param);
778  param.sched_priority = sched_get_priority_min(sched_policy);
779  pthread_setschedparam(d->thread_id, sched_policy, &param);
780  }
781 # else
782  Q_UNUSED(status);
783 # endif // SCHED_IDLE
784 #endif
785 }
double d
Definition: qnumeric_p.h:62
static LibLoadStatus status
Definition: qlocale_icu.cpp:69
static bool calculateUnixPriority(int priority, int *sched_policy, int *sched_priority)
#define Q_D(Class)
Definition: qglobal.h:2482
Priority priority() const
Returns the priority for a running thread.
Definition: qthread.cpp:718
#define SCHED_IDLE
Q_CORE_EXPORT void qWarning(const char *,...)
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
int errno

◆ setStackSize()

void QThread::setStackSize ( uint  stackSize)

Sets the maximum stack size for the thread to stackSize.

If stackSize is greater than zero, the maximum stack size is set to stackSize bytes, otherwise the maximum stack size is automatically determined by the operating system.

Warning
Most operating systems place minimum and maximum limits on thread stack sizes. The thread will fail to start if the stack size is outside these limits.
See also
stackSize()

Definition at line 519 of file qthread.cpp.

520 {
521  Q_D(QThread);
522  QMutexLocker locker(&d->mutex);
523  Q_ASSERT_X(!d->running, "QThread::setStackSize",
524  "cannot change stack size while the thread is running");
525  d->stackSize = stackSize;
526 }
double d
Definition: qnumeric_p.h:62
uint stackSize() const
Returns the maximum stack size for the thread (if set with setStackSize()); otherwise returns zero...
Definition: qthread.cpp:534
#define Q_D(Class)
Definition: qglobal.h:2482
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ setTerminationEnabled()

void QThread::setTerminationEnabled ( bool  enabled = true)
staticprotected

Enables or disables termination of the current thread based on the enabled parameter.

The thread must have been started by QThread.

When enabled is false, termination is disabled. Future calls to QThread::terminate() will return immediately without effect. Instead, the termination is deferred until termination is enabled.

When enabled is true, termination is enabled. Future calls to QThread::terminate() will terminate the thread normally. If termination has been deferred (i.e. QThread::terminate() was called with termination disabled), this function will terminate the calling thread immediately. Note that this function will not return in this case.

See also
terminate()

Definition at line 726 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and qt_adopted_thread_watcher_function().

727 {
728  QThread *thr = currentThread();
729  Q_ASSERT_X(thr != 0, "QThread::setTerminationEnabled()",
730  "Current thread was not started with QThread.");
731 
732  Q_UNUSED(thr)
733  pthread_setcancelstate(enabled ? PTHREAD_CANCEL_ENABLE : PTHREAD_CANCEL_DISABLE, NULL);
734  if (enabled)
736 }
static QThread * currentThread()
Returns a pointer to a QThread which manages the currently executing thread.
Definition: qthread.cpp:419
int pthread_setcancelstate(int, int *)
void pthread_testcancel(void)
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
#define enabled

◆ sleep()

void QThread::sleep ( unsigned long  secs)
staticprotected

Forces the current thread to sleep for secs seconds.

See also
msleep(), usleep()

Definition at line 499 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish().

500 {
501  struct timeval tv;
502  gettimeofday(&tv, 0);
503  struct timespec ti;
504  ti.tv_sec = tv.tv_sec + secs;
505  ti.tv_nsec = (tv.tv_usec * 1000);
506  thread_sleep(&ti);
507 }
static void thread_sleep(struct timespec *ti)

◆ stackSize()

uint QThread::stackSize ( ) const

Returns the maximum stack size for the thread (if set with setStackSize()); otherwise returns zero.

See also
setStackSize()

Definition at line 534 of file qthread.cpp.

Referenced by setStackSize().

535 {
536  Q_D(const QThread);
537  QMutexLocker locker(&d->mutex);
538  return d->stackSize;
539 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ start

void QThread::start ( Priority  priority = InheritPriority)
slot

Begins execution of the thread by calling run().

The operating system will schedule the thread according to the priority parameter. If the thread is already running, this function does nothing.

The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler for more details).

See also
run(), terminate()

Definition at line 583 of file qthread_unix.cpp.

Referenced by QInotifyFileSystemWatcherEngine::addPaths(), QKqueueFileSystemWatcherEngine::addPaths(), QWindowsFileSystemWatcherEngine::addPaths(), QPollingFileSystemWatcherEngine::addPaths(), QCoreWlanEngine::doRequestUpdate(), QThreadPrivate::finish(), QEventDispatcherQPAPrivate::hasIntegration(), QNetworkConfigurationManagerPrivate::initialize(), QDirectFbIntegration::initializeInput(), QProcessPrivate::pipeWriterBytesToWrite(), QNetworkAccessHttpBackend::postRequest(), QBBIntegration::QBBIntegration(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::QDeclarativeXmlQueryEngine(), QFileInfoGatherer::QFileInfoGatherer(), QIntMouseHandler::QIntMouseHandler(), QNlaEngine::QNlaEngine(), QWSIntKbPrivate::QWSIntKbPrivate(), QProcessPrivate::startDetached(), QDnotifySignalThread::startNotify(), QProcessPrivate::startProcess(), QThreadPoolPrivate::startThread(), QThreadPoolPrivate::tryStart(), and QFSEventsFileSystemWatcherEngine::warmUpFSEvents().

584 {
585  Q_D(QThread);
586  QMutexLocker locker(&d->mutex);
587 
588  if (d->isInFinish)
589  d->thread_done.wait(locker.mutex());
590 
591  if (d->running)
592  return;
593 
594  d->running = true;
595  d->finished = false;
596  d->terminated = false;
597  d->returnCode = 0;
598  d->exited = false;
599 
600  pthread_attr_t attr;
601  pthread_attr_init(&attr);
602  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
603 
604  d->priority = priority;
605 
606 #if defined(QT_HAS_THREAD_PRIORITY_SCHEDULING)
607  switch (priority) {
608  case InheritPriority:
609  {
610  pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
611  break;
612  }
613 
614  default:
615  {
616  int sched_policy;
617  if (pthread_attr_getschedpolicy(&attr, &sched_policy) != 0) {
618  // failed to get the scheduling policy, don't bother
619  // setting the priority
620  qWarning("QThread::start: Cannot determine default scheduler policy");
621  break;
622  }
623 
624  int prio;
625  if (!calculateUnixPriority(priority, &sched_policy, &prio)) {
626  // failed to get the scheduling parameters, don't
627  // bother setting the priority
628  qWarning("QThread::start: Cannot determine scheduler priority range");
629  break;
630  }
631 
632  sched_param sp;
633  sp.sched_priority = prio;
634 
635  if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0
636  || pthread_attr_setschedpolicy(&attr, sched_policy) != 0
637  || pthread_attr_setschedparam(&attr, &sp) != 0) {
638  // could not set scheduling hints, fallback to inheriting them
639  // we'll try again from inside the thread
640  pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
642  }
643  break;
644  }
645  }
646 #endif // QT_HAS_THREAD_PRIORITY_SCHEDULING
647 
648 
649  if (d->stackSize > 0) {
650 #if defined(_POSIX_THREAD_ATTR_STACKSIZE) && (_POSIX_THREAD_ATTR_STACKSIZE-0 > 0)
651  int code = pthread_attr_setstacksize(&attr, d->stackSize);
652 #else
653  int code = ENOSYS; // stack size not supported, automatically fail
654 #endif // _POSIX_THREAD_ATTR_STACKSIZE
655 
656  if (code) {
657  qWarning("QThread::start: Thread stack size error: %s",
658  qPrintable(qt_error_string(code)));
659 
660  // we failed to set the stacksize, and as the documentation states,
661  // the thread will fail to run...
662  d->running = false;
663  d->finished = false;
664  return;
665  }
666  }
667 
668  int code =
669  pthread_create(&d->thread_id, &attr, QThreadPrivate::start, this);
670  if (code == EPERM) {
671  // caller does not have permission to set the scheduling
672  // parameters/policy
673  pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
674  code =
675  pthread_create(&d->thread_id, &attr, QThreadPrivate::start, this);
676  }
677 
678  pthread_attr_destroy(&attr);
679 
680  if (code) {
681  qWarning("QThread::start: Thread creation error: %s", qPrintable(qt_error_string(code)));
682 
683  d->running = false;
684  d->finished = false;
685  d->thread_id = 0;
686  }
687 }
double d
Definition: qnumeric_p.h:62
QString qt_error_string(int errorCode)
Definition: qglobal.cpp:2600
static void * start(void *arg)
static bool calculateUnixPriority(int priority, int *sched_policy, int *sched_priority)
#define Q_D(Class)
Definition: qglobal.h:2482
Priority
This enum type indicates how the operating system should schedule newly created threads.
Definition: qthread.h:70
Priority priority() const
Returns the priority for a running thread.
Definition: qthread.cpp:718
Q_CORE_EXPORT void qWarning(const char *,...)
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
#define qPrintable(string)
Definition: qglobal.h:1750
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59
int pthread_attr_setinheritsched(pthread_attr_t *, int)

◆ started

void QThread::started ( )
signal

This signal is emitted when the thread starts executing.

See also
finished(), terminated()

Referenced by qt_adopted_thread_watcher_function(), and QThreadPrivate::start().

◆ terminate

void QThread::terminate ( )
slot

Terminates the execution of the thread.

The thread may or may not be terminated immediately, depending on the operating system's scheduling policies. Listen for the terminated() signal, or use QThread::wait() after terminate(), to be sure.

When the thread is terminated, all threads waiting for the thread to finish will be woken up.

Warning
This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

Termination can be explicitly enabled or disabled by calling QThread::setTerminationEnabled(). Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of QThread::setTerminationEnabled() for more information.

See also
setTerminationEnabled()

Definition at line 689 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and QWindowsPipeWriter::~QWindowsPipeWriter().

690 {
691  Q_D(QThread);
692  QMutexLocker locker(&d->mutex);
693 
694  if (!d->thread_id)
695  return;
696 
697  int code = pthread_cancel(d->thread_id);
698  if (code) {
699  qWarning("QThread::start: Thread termination error: %s",
700  qPrintable(qt_error_string((code))));
701  } else {
702  d->terminated = true;
703  }
704 }
double d
Definition: qnumeric_p.h:62
QString qt_error_string(int errorCode)
Definition: qglobal.cpp:2600
#define Q_D(Class)
Definition: qglobal.h:2482
int pthread_cancel(pthread_t)
Q_CORE_EXPORT void qWarning(const char *,...)
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
#define qPrintable(string)
Definition: qglobal.h:1750
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ terminated

void QThread::terminated ( )
signal

This signal is emitted when the thread is terminated.

See also
started(), finished()

Referenced by QThreadPrivate::finish().

◆ usleep()

void QThread::usleep ( unsigned long  usecs)
staticprotected

Forces the current thread to sleep for usecs microseconds.

See also
sleep(), msleep()

Definition at line 521 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish().

522 {
523  struct timeval tv;
524  gettimeofday(&tv, 0);
525  struct timespec ti;
526 
527  ti.tv_nsec = (tv.tv_usec + (usecs % 1000000)) * 1000;
528  ti.tv_sec = tv.tv_sec + (usecs / 1000000) + (ti.tv_nsec / 1000000000);
529  ti.tv_nsec %= 1000000000;
530  thread_sleep(&ti);
531 }
static void thread_sleep(struct timespec *ti)

◆ wait()

bool QThread::wait ( unsigned long  time = ULONG_MAX)

Blocks the thread until either of these conditions is met:

  • The thread associated with this QThread object has finished execution (i.

    e. when it returns from run()). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.

  • time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the thread must return from run()). This function will return false if the wait timed out.

This provides similar functionality to the POSIX pthread_join() function.

See also
sleep(), terminate()

Definition at line 706 of file qthread_unix.cpp.

Referenced by QFSEventsFileSystemWatcherEngine::addPaths(), QNetworkConfigurationManagerPrivate::cleanup(), QThreadPrivate::finish(), QNetworkAccessHttpBackend::postRequest(), QScanThread::quit(), QKqueueFileSystemWatcherEngine::removePaths(), QWindowsFileSystemWatcherEngine::removePaths(), QFSEventsFileSystemWatcherEngine::removePaths(), QPollingFileSystemWatcherEngine::removePaths(), QThreadPoolPrivate::reset(), QBBScreenEventThread::shutdown(), QDeclarativePixmapReader::~QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::~QDeclarativeXmlQueryEngine(), QDirectFbIntegration::~QDirectFbIntegration(), QDnotifySignalThread::~QDnotifySignalThread(), QFileInfoGatherer::~QFileInfoGatherer(), QIntMousePrivate::~QIntMousePrivate(), QKqueueFileSystemWatcherEngine::~QKqueueFileSystemWatcherEngine(), QNlaThread::~QNlaThread(), ~QThread(), QWindowsFileSystemWatcherEngine::~QWindowsFileSystemWatcherEngine(), QWindowsPipeWriter::~QWindowsPipeWriter(), and QWSIntKbPrivate::~QWSIntKbPrivate().

707 {
708  Q_D(QThread);
709  QMutexLocker locker(&d->mutex);
710 
711  if (d->thread_id == pthread_self()) {
712  qWarning("QThread::wait: Thread tried to wait on itself");
713  return false;
714  }
715 
716  if (d->finished || !d->running)
717  return true;
718 
719  while (d->running) {
720  if (!d->thread_done.wait(locker.mutex(), time))
721  return false;
722  }
723  return true;
724 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59

◆ yieldCurrentThread()

void QThread::yieldCurrentThread ( )
static

Yields execution of the current thread to another runnable thread, if any.

Note that the operating system decides to which thread to switch.

Definition at line 474 of file qthread_unix.cpp.

Referenced by QThreadPrivate::finish(), and QMutex::lockInternal().

475 {
476  sched_yield();
477 }

Friends and Related Functions

◆ QCoreApplication

friend class QCoreApplication
friend

Definition at line 135 of file qthread.h.

◆ QThreadData

friend class QThreadData
friend

Definition at line 136 of file qthread.h.


The documentation for this class was generated from the following files: