source: trunk/src/corelib/thread/qthread.cpp@ 1050

Last change on this file since 1050 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 21.5 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qthread.h"
43#include "qthreadstorage.h"
44#include "qmutex.h"
45#include "qmutexpool_p.h"
46#include "qreadwritelock.h"
47#include "qabstracteventdispatcher.h"
48
49#include <qeventloop.h>
50#include <qhash.h>
51
52#include "qthread_p.h"
53#include "private/qcoreapplication_p.h"
54
55/*
56#ifdef Q_OS_WIN32
57# include "qt_windows.h"
58#else
59# include <unistd.h>
60# include <netinet/in.h>
61# include <sys/utsname.h>
62# include <sys/socket.h>
63*/
64/*
65# elif defined(Q_OS_HPUX)
66# include <sys/pstat.h>
67# elif defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) || defined(Q_OS_MAC)
68# include <sys/sysctl.h>
69# endif
70#endif
71*/
72
73QT_BEGIN_NAMESPACE
74
75/*
76 QThreadData
77*/
78
79QThreadData::QThreadData(int initialRefCount)
80 : _ref(initialRefCount), thread(0),
81 quitNow(false), loopLevel(0), eventDispatcher(0), canWait(true)
82{
83 // fprintf(stderr, "QThreadData %p created\n", this);
84}
85
86QThreadData::~QThreadData()
87{
88 Q_ASSERT(_ref == 0);
89
90 // In the odd case that Qt is running on a secondary thread, the main
91 // thread instance will have been dereffed asunder because of the deref in
92 // QThreadData::current() and the deref in the pthread_destroy. To avoid
93 // crashing during QCoreApplicationData's global static cleanup we need to
94 // safeguard the main thread here.. This fix is a bit crude, but it solves
95 // the problem...
96 if (this->thread == QCoreApplicationPrivate::theMainThread) {
97 QCoreApplicationPrivate::theMainThread = 0;
98 }
99
100 QThread *t = thread;
101 thread = 0;
102 delete t;
103
104 for (int i = 0; i < postEventList.size(); ++i) {
105 const QPostEvent &pe = postEventList.at(i);
106 if (pe.event) {
107 --pe.receiver->d_func()->postedEvents;
108 pe.event->posted = false;
109 delete pe.event;
110 }
111 }
112
113 // fprintf(stderr, "QThreadData %p destroyed\n", this);
114}
115
116void QThreadData::ref()
117{
118#ifndef QT_NO_THREAD
119 (void) _ref.ref();
120 Q_ASSERT(_ref != 0);
121#endif
122}
123
124void QThreadData::deref()
125{
126#ifndef QT_NO_THREAD
127 if (!_ref.deref())
128 delete this;
129#endif
130}
131
132/*
133 QAdoptedThread
134*/
135
136QAdoptedThread::QAdoptedThread(QThreadData *data)
137 : QThread(*new QThreadPrivate(data))
138{
139 // thread should be running and not finished for the lifetime
140 // of the application (even if QCoreApplication goes away)
141#ifndef QT_NO_THREAD
142 d_func()->running = true;
143 d_func()->finished = false;
144 init();
145#endif
146
147 // fprintf(stderr, "new QAdoptedThread = %p\n", this);
148}
149
150QAdoptedThread::~QAdoptedThread()
151{
152#ifndef QT_NO_THREAD
153 QThreadPrivate::finish(this);
154#endif
155 // fprintf(stderr, "~QAdoptedThread = %p\n", this);
156}
157
158QThread *QAdoptedThread::createThreadForAdoption()
159{
160 QScopedPointer<QThread> t(new QAdoptedThread(0));
161 t->moveToThread(t.data());
162 return t.take();
163}
164
165void QAdoptedThread::run()
166{
167 // this function should never be called
168 qFatal("QAdoptedThread::run(): Internal error, this implementation should never be called.");
169}
170#ifndef QT_NO_THREAD
171/*
172 QThreadPrivate
173*/
174
175QThreadPrivate::QThreadPrivate(QThreadData *d)
176 : QObjectPrivate(), running(false), finished(false), terminated(false), exited(false), returnCode(-1),
177 stackSize(0), priority(QThread::InheritPriority), data(d)
178{
179#if defined (Q_OS_UNIX)
180 thread_id = 0;
181#elif defined (Q_WS_WIN)
182 handle = 0;
183 id = 0;
184 waiters = 0;
185#endif
186#if defined (Q_WS_WIN) || defined (Q_OS_SYMBIAN)
187 terminationEnabled = true;
188 terminatePending = false;
189#endif
190#if defined (Q_OS_OS2)
191 tid = 0;
192 terminationEnabled = true;
193 terminatePending = false;
194#endif
195
196 if (!data)
197 data = new QThreadData;
198}
199
200QThreadPrivate::~QThreadPrivate()
201{
202 data->deref();
203}
204
205/*!
206 \class QThread
207 \brief The QThread class provides platform-independent threads.
208
209 \ingroup thread
210
211 A QThread represents a separate thread of control within the
212 program; it shares data with all the other threads within the
213 process but executes independently in the way that a separate
214 program does on a multitasking operating system. Instead of
215 starting in \c main(), QThreads begin executing in run(). By
216 default, run() starts the event loop by calling exec() (see
217 below). To create your own threads, subclass QThread and
218 reimplement run(). For example:
219
220 \snippet doc/src/snippets/code/src_corelib_thread_qthread.cpp 0
221
222 This will create a QTcpSocket in the thread and then execute the
223 thread's event loop. Use the start() method to begin execution.
224 Execution ends when you return from run(), just as an application
225 does when it leaves main(). QThread will notifiy you via a signal
226 when the thread is started(), finished(), and terminated(), or
227 you can use isFinished() and isRunning() to query the state of
228 the thread. Use wait() to block until the thread has finished
229 execution.
230
231 Each thread gets its own stack from the operating system. The
232 operating system also determines the default size of the stack.
233 You can use setStackSize() to set a custom stack size.
234
235 Each QThread can have its own event loop. You can start the event
236 loop by calling exec(); you can stop it by calling exit() or
237 quit(). Having an event loop in a thread makes it possible to
238 connect signals from other threads to slots in this thread, using
239 a mechanism called \l{Qt::QueuedConnection}{queued
240 connections}. It also makes it possible to use classes that
241 require the event loop, such as QTimer and QTcpSocket, in the
242 thread. Note, however, that it is not possible to use any widget
243 classes in the thread.
244
245 In extreme cases, you may want to forcibly terminate() an
246 executing thread. However, doing so is dangerous and discouraged.
247 Please read the documentation for terminate() and
248 setTerminationEnabled() for detailed information.
249
250 The static functions currentThreadId() and currentThread() return
251 identifiers for the currently executing thread. The former
252 returns a platform specific ID for the thread; the latter returns
253 a QThread pointer.
254
255 QThread also provides platform independent sleep functions in
256 varying resolutions. Use sleep() for full second resolution,
257 msleep() for millisecond resolution, and usleep() for microsecond
258 resolution.
259
260 \sa {Thread Support in Qt}, QThreadStorage, QMutex, QSemaphore, QWaitCondition,
261 {Mandelbrot Example}, {Semaphores Example}, {Wait Conditions Example}
262*/
263
264/*!
265 \fn Qt::HANDLE QThread::currentThreadId()
266
267 Returns the thread handle of the currently executing thread.
268
269 \warning The handle returned by this function is used for internal
270 purposes and should not be used in any application code.
271
272 \warning On Windows, the returned value is a pseudo-handle for the
273 current thread. It can't be used for numerical comparison. i.e.,
274 this function returns the DWORD (Windows-Thread ID) returned by
275 the Win32 function getCurrentThreadId(), not the HANDLE
276 (Windows-Thread HANDLE) returned by the Win32 function
277 getCurrentThread().
278*/
279
280/*!
281 \fn int QThread::idealThreadCount()
282
283 Returns the ideal number of threads that can be run on the system. This is done querying
284 the number of processor cores, both real and logical, in the system. This function returns -1
285 if the number of processor cores could not be detected.
286*/
287
288/*!
289 \fn void QThread::yieldCurrentThread()
290
291 Yields execution of the current thread to another runnable thread,
292 if any. Note that the operating system decides to which thread to
293 switch.
294*/
295
296/*!
297 \fn void QThread::start(Priority priority)
298
299 Begins execution of the thread by calling run(), which should be
300 reimplemented in a QThread subclass to contain your code. The
301 operating system will schedule the thread according to the \a
302 priority parameter. If the thread is already running, this
303 function does nothing.
304
305 The effect of the \a priority parameter is dependent on the
306 operating system's scheduling policy. In particular, the \a priority
307 will be ignored on systems that do not support thread priorities
308 (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler
309 for more details).
310
311 \sa run(), terminate()
312*/
313
314/*!
315 \fn void QThread::started()
316
317 This signal is emitted when the thread starts executing.
318
319 \sa finished(), terminated()
320*/
321
322/*!
323 \fn void QThread::finished()
324
325 This signal is emitted when the thread has finished executing.
326
327 \sa started(), terminated()
328*/
329
330/*!
331 \fn void QThread::terminated()
332
333 This signal is emitted when the thread is terminated.
334
335 \sa started(), finished()
336*/
337
338/*!
339 \enum QThread::Priority
340
341 This enum type indicates how the operating system should schedule
342 newly created threads.
343
344 \value IdlePriority scheduled only when no other threads are
345 running.
346
347 \value LowestPriority scheduled less often than LowPriority.
348 \value LowPriority scheduled less often than NormalPriority.
349
350 \value NormalPriority the default priority of the operating
351 system.
352
353 \value HighPriority scheduled more often than NormalPriority.
354 \value HighestPriority scheduled more often than HighPriority.
355
356 \value TimeCriticalPriority scheduled as often as possible.
357
358 \value InheritPriority use the same priority as the creating
359 thread. This is the default.
360*/
361
362/*!
363 Returns a pointer to a QThread which represents the currently
364 executing thread.
365*/
366QThread *QThread::currentThread()
367{
368 QThreadData *data = QThreadData::current();
369 Q_ASSERT(data != 0);
370 return data->thread;
371}
372
373/*!
374 Constructs a new thread with the given \a parent. The thread does
375 not begin executing until start() is called.
376
377 \sa start()
378*/
379QThread::QThread(QObject *parent)
380 : QObject(*(new QThreadPrivate), parent)
381{
382 Q_D(QThread);
383 // fprintf(stderr, "QThreadData %p created for thread %p\n", d->data, this);
384 d->data->thread = this;
385}
386
387/*! \internal
388 */
389QThread::QThread(QThreadPrivate &dd, QObject *parent)
390 : QObject(dd, parent)
391{
392 Q_D(QThread);
393 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
394 d->data->thread = this;
395}
396
397/*!
398 Destroys the thread.
399
400 Note that deleting a QThread object will not stop the execution
401 of the thread it represents. Deleting a running QThread (i.e.
402 isFinished() returns false) will probably result in a program
403 crash. You can wait() on a thread to make sure that it has
404 finished.
405*/
406QThread::~QThread()
407{
408 Q_D(QThread);
409 {
410 QMutexLocker locker(&d->mutex);
411 if (d->running && !d->finished)
412 qWarning("QThread: Destroyed while thread is still running");
413
414 d->data->thread = 0;
415 }
416}
417
418/*!
419 Returns true if the thread is finished; otherwise returns false.
420
421 \sa isRunning()
422*/
423bool QThread::isFinished() const
424{
425 Q_D(const QThread);
426 QMutexLocker locker(&d->mutex);
427 return d->finished;
428}
429
430/*!
431 Returns true if the thread is running; otherwise returns false.
432
433 \sa isFinished()
434*/
435bool QThread::isRunning() const
436{
437 Q_D(const QThread);
438 QMutexLocker locker(&d->mutex);
439 return d->running;
440}
441
442/*!
443 Sets the maximum stack size for the thread to \a stackSize. If \a
444 stackSize is greater than zero, the maximum stack size is set to
445 \a stackSize bytes, otherwise the maximum stack size is
446 automatically determined by the operating system.
447
448 \warning Most operating systems place minimum and maximum limits
449 on thread stack sizes. The thread will fail to start if the stack
450 size is outside these limits.
451
452 \sa stackSize()
453*/
454void QThread::setStackSize(uint stackSize)
455{
456 Q_D(QThread);
457 QMutexLocker locker(&d->mutex);
458 Q_ASSERT_X(!d->running, "QThread::setStackSize",
459 "cannot change stack size while the thread is running");
460 d->stackSize = stackSize;
461}
462
463/*!
464 Returns the maximum stack size for the thread (if set with
465 setStackSize()); otherwise returns zero.
466
467 \sa setStackSize()
468*/
469uint QThread::stackSize() const
470{
471 Q_D(const QThread);
472 QMutexLocker locker(&d->mutex);
473 return d->stackSize;
474}
475
476/*!
477 Enters the event loop and waits until exit() is called, returning the value
478 that was passed to exit(). The value returned is 0 if exit() is called via
479 quit().
480
481 It is necessary to call this function to start event handling.
482
483 \sa quit(), exit()
484*/
485int QThread::exec()
486{
487 Q_D(QThread);
488 QMutexLocker locker(&d->mutex);
489 d->data->quitNow = false;
490 if (d->exited) {
491 d->exited = false;
492 return d->returnCode;
493 }
494 locker.unlock();
495
496 QEventLoop eventLoop;
497 int returnCode = eventLoop.exec();
498
499 locker.relock();
500 d->exited = false;
501 d->returnCode = -1;
502 return returnCode;
503}
504
505/*!
506 Tells the thread's event loop to exit with a return code.
507
508 After calling this function, the thread leaves the event loop and
509 returns from the call to QEventLoop::exec(). The
510 QEventLoop::exec() function returns \a returnCode.
511
512 By convention, a \a returnCode of 0 means success, any non-zero value
513 indicates an error.
514
515 Note that unlike the C library function of the same name, this
516 function \e does return to the caller -- it is event processing
517 that stops.
518
519 This function does nothing if the thread does not have an event
520 loop.
521
522 \sa quit() QEventLoop
523*/
524void QThread::exit(int returnCode)
525{
526 Q_D(QThread);
527 QMutexLocker locker(&d->mutex);
528 d->exited = true;
529 d->returnCode = returnCode;
530 d->data->quitNow = true;
531 for (int i = 0; i < d->data->eventLoops.size(); ++i) {
532 QEventLoop *eventLoop = d->data->eventLoops.at(i);
533 eventLoop->exit(returnCode);
534 }
535}
536
537/*!
538 Tells the thread's event loop to exit with return code 0 (success).
539 Equivalent to calling QThread::exit(0).
540
541 This function does nothing if the thread does not have an event
542 loop.
543
544 \sa exit() QEventLoop
545*/
546void QThread::quit()
547{ exit(); }
548
549/*!
550 The starting point for the thread. After calling start(), the
551 newly created thread calls this function. The default
552 implementation simply calls exec().
553
554 You can reimplemented this function to do other useful
555 work. Returning from this method will end the execution of the
556 thread.
557
558 \sa start() wait()
559*/
560void QThread::run()
561{
562 (void) exec();
563}
564
565/*! \internal
566 Initializes the QThread system.
567*/
568#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
569void qt_create_tls();
570#endif
571
572void QThread::initialize()
573{
574 if (qt_global_mutexpool)
575 return;
576 qt_global_mutexpool = QMutexPool::instance();
577
578#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
579 qt_create_tls();
580#endif
581}
582
583
584/*! \internal
585 Cleans up the QThread system.
586*/
587void QThread::cleanup()
588{
589 qt_global_mutexpool = 0;
590}
591
592/*!
593 \fn bool QThread::finished() const
594
595 Use isFinished() instead.
596*/
597
598/*!
599 \fn bool QThread::running() const
600
601 Use isRunning() instead.
602*/
603
604/*! \fn void QThread::setPriority(Priority priority)
605 \since 4.1
606
607 This function sets the \a priority for a running thread. If the
608 thread is not running, this function does nothing and returns
609 immediately. Use start() to start a thread with a specific
610 priority.
611
612 The \a priority argument can be any value in the \c
613 QThread::Priority enum except for \c InheritPriorty.
614
615 The effect of the \a priority parameter is dependent on the
616 operating system's scheduling policy. In particular, the \a priority
617 will be ignored on systems that do not support thread priorities
618 (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler
619 for more details).
620
621 \sa Priority priority() start()
622*/
623
624/*!
625 \since 4.1
626
627 Returns the priority for a running thread. If the thread is not
628 running, this function returns \c InheritPriority.
629
630 \sa Priority setPriority() start()
631*/
632QThread::Priority QThread::priority() const
633{
634 Q_D(const QThread);
635 QMutexLocker locker(&d->mutex);
636
637 // mask off the high bits that are used for flags
638 return Priority(d->priority & 0xffff);
639}
640
641/*!
642 \fn void QThread::sleep(unsigned long secs)
643
644 Forces the current thread to sleep for \a secs seconds.
645
646 \sa msleep(), usleep()
647*/
648
649/*!
650 \fn void QThread::msleep(unsigned long msecs)
651
652 Causes the current thread to sleep for \a msecs milliseconds.
653
654 \sa sleep(), usleep()
655*/
656
657/*!
658 \fn void QThread::usleep(unsigned long usecs)
659
660 Causes the current thread to sleep for \a usecs microseconds.
661
662 \sa sleep(), msleep()
663*/
664
665/*!
666 \fn void QThread::terminate()
667
668 Terminates the execution of the thread. The thread may or may not
669 be terminated immediately, depending on the operating systems
670 scheduling policies. Use QThread::wait() after terminate() for
671 synchronous termination.
672
673 When the thread is terminated, all threads waiting for the thread
674 to finish will be woken up.
675
676 \warning This function is dangerous and its use is discouraged.
677 The thread can be terminated at any point in its code path.
678 Threads can be terminated while modifying data. There is no
679 chance for the thread to clean up after itself, unlock any held
680 mutexes, etc. In short, use this function only if absolutely
681 necessary.
682
683 Termination can be explicitly enabled or disabled by calling
684 QThread::setTerminationEnabled(). Calling this function while
685 termination is disabled results in the termination being
686 deferred, until termination is re-enabled. See the documentation
687 of QThread::setTerminationEnabled() for more information.
688
689 \sa setTerminationEnabled()
690*/
691
692/*!
693 \fn bool QThread::wait(unsigned long time)
694
695 Blocks the thread until either of these conditions is met:
696
697 \list
698 \o The thread associated with this QThread object has finished
699 execution (i.e. when it returns from \l{run()}). This function
700 will return true if the thread has finished. It also returns
701 true if the thread has not been started yet.
702 \o \a time milliseconds has elapsed. If \a time is ULONG_MAX (the
703 default), then the wait will never timeout (the thread must
704 return from \l{run()}). This function will return false if the
705 wait timed out.
706 \endlist
707
708 This provides similar functionality to the POSIX \c
709 pthread_join() function.
710
711 \sa sleep(), terminate()
712*/
713
714/*!
715 \fn void QThread::setTerminationEnabled(bool enabled)
716
717 Enables or disables termination of the current thread based on the
718 \a enabled parameter. The thread must have been started by
719 QThread.
720
721 When \a enabled is false, termination is disabled. Future calls
722 to QThread::terminate() will return immediately without effect.
723 Instead, the termination is deferred until termination is enabled.
724
725 When \a enabled is true, termination is enabled. Future calls to
726 QThread::terminate() will terminate the thread normally. If
727 termination has been deferred (i.e. QThread::terminate() was
728 called with termination disabled), this function will terminate
729 the calling thread \e immediately. Note that this function will
730 not return in this case.
731
732 \sa terminate()
733*/
734
735#else // QT_NO_THREAD
736
737QThread::QThread(QObject *parent)
738 : QObject(*(new QThreadPrivate), (QObject*)0){
739 Q_D(QThread);
740 d->data->thread = this;
741}
742
743QThread *QThread::currentThread()
744{
745 return QThreadData::current()->thread;
746}
747
748QThreadData* QThreadData::current()
749{
750 static QThreadData *data = 0; // reinterpret_cast<QThreadData *>(pthread_getspecific(current_thread_data_key));
751 if (!data) {
752 QScopedPointer<QThreadData> newdata(new QThreadData);
753 newdata->thread = new QAdoptedThread(newdata.data());
754 data = newdata.take();
755 data->deref();
756 }
757 return data;
758}
759
760/*! \internal
761 */
762QThread::QThread(QThreadPrivate &dd, QObject *parent)
763 : QObject(dd, parent)
764{
765 Q_D(QThread);
766 // fprintf(stderr, "QThreadData %p taken from private data for thread %p\n", d->data, this);
767 d->data->thread = this;
768}
769
770#endif // QT_NO_THREAD
771
772QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.