summaryrefslogtreecommitdiffstats
path: root/src/kernel/qthread_unix.cpp
blob: bc492af1111d7cba8a6caf8a3400e7ad73aef304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/****************************************************************************
**
** QThread class for Unix
**
** Copyright (C) 1992-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the files LICENSE.GPL2
** and LICENSE.GPL3 included in the packaging of this file.
** Alternatively you may (at your option) use any later version
** of the GNU General Public License if such license has been
** publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free Qt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.QPL
** included in the packaging of this file.  Licensees holding valid Qt
** Commercial licenses may use this file in accordance with the Qt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/

#if defined(QT_THREAD_SUPPORT)

#include "qplatformdefs.h"

typedef pthread_mutex_t Q_MUTEX_T;

#include "qthread.h"
#include <private/qthreadinstance_p.h>
#include <private/qmutex_p.h>
#include <private/qmutexpool_p.h>
#include <qthreadstorage.h>
#include <qapplication.h>

#include <errno.h>
#include <sched.h>

#if defined(QT_USE_GLIBMAINLOOP)
#include <glib.h>
#endif // QT_USE_GLIBMAINLOOP

static QMutexPool *qt_thread_mutexpool = 0;

#if defined(Q_C_CALLBACKS)
extern "C" {
#endif

typedef void*(*QtThreadCallback)(void*);

static pthread_once_t storage_key_once = PTHREAD_ONCE_INIT;
static pthread_key_t storage_key;
static void create_storage_key()
{
    pthread_key_create( &storage_key, NULL );
}

#if defined(Q_C_CALLBACKS)
}
#endif


/**************************************************************************
 ** QThreadInstance
 *************************************************************************/

void QThreadInstance::setCurrentThread(QThread *thread)
{
    pthread_once(&storage_key_once, create_storage_key);
    pthread_setspecific(storage_key, thread);
}

QThreadInstance *QThreadInstance::current()
{
    QThreadInstance *ret = NULL;
    pthread_once( &storage_key_once, create_storage_key );
    QThread *thread = (QThread *) pthread_getspecific( storage_key );
    if (thread) {
        ret = thread->d;
    }
    return ret;
}

void QThreadInstance::init(unsigned int stackSize)
{
    stacksize = stackSize;
    args[0] = args[1] = 0;
    thread_storage = 0;
    finished = FALSE;
    running = FALSE;
    orphan = FALSE;
    disableThreadPostedEvents = FALSE;

    pthread_cond_init(&thread_done, NULL);
    thread_id = 0;

    eventLoop = 0;
    cleanupType = QThread::CleanupMergeObjects;

    // threads have not been initialized yet, do it now
    if (! qt_thread_mutexpool) QThread::initialize();
}

void QThreadInstance::deinit()
{
    pthread_cond_destroy(&thread_done);
}

void *QThreadInstance::start( void *_arg )
{
    void **arg = (void **) _arg;

#if defined(QT_USE_GLIBMAINLOOP)
    // This is the first time we have access to the native pthread ID of this newly created thread
    ((QThreadInstance*)arg[1])->thread_id = pthread_self();
#endif // QT_USE_GLIBMAINLOOP

#ifdef QT_DEBUG
    qDebug("QThreadInstance::start: Setting thread storage to %p\n", (QThread *) arg[0]);
#endif // QT_DEBUG
    setCurrentThread( (QThread *) arg[0] );

    pthread_cleanup_push( QThreadInstance::finish, arg[1] );
    pthread_testcancel();

    ( (QThread *) arg[0] )->run();

    pthread_cleanup_pop( TRUE );
    return 0;
}

void QThreadInstance::finish( void * )
{
    QThreadInstance *d = current();

    if ( ! d ) {
#ifdef QT_CHECK_STATE
	qWarning( "QThread: internal error: zero data for running thread." );
#endif // QT_CHECK_STATE
	return;
    }

#ifdef QT_DEBUG
    qDebug("QThreadInstance::finish: In QThreadInstance::finish for thread %p\n", (QThread*)d->args[0]);
#endif // QT_DEBUG

    QApplication::threadTerminationHandler((QThread*)d->args[0]);

    QMutexLocker locker( d->mutex() );
    d->running = FALSE;
    d->finished = TRUE;
    d->args[0] = d->args[1] = 0;


    QThreadStorageData::finish( d->thread_storage );
    d->thread_storage = 0;

    d->thread_id = 0;
    pthread_cond_broadcast(&d->thread_done);

    if (d->orphan) {
        d->deinit();
	delete d;
    }
}

QMutex *QThreadInstance::mutex() const
{
    return qt_thread_mutexpool ? qt_thread_mutexpool->get( (void *) this ) : 0;
}

void QThreadInstance::terminate()
{
    if ( ! thread_id ) return;
    pthread_cancel( thread_id );
}

/**************************************************************************
 ** QThread
 *************************************************************************/

/*!
    This returns the thread handle of the currently executing thread.

    \warning The handle returned by this function is used for internal
    purposes and should \e not be used in any application code. On
    Windows, the returned value is a pseudo handle for the current
    thread, and it cannot be used for numerical comparison.
*/
Qt::HANDLE QThread::currentThread()
{
    return (HANDLE) pthread_self();
}

/*! \internal
  Initializes the QThread system.
*/
void QThread::initialize()
{
    if ( ! qt_global_mutexpool )
	qt_global_mutexpool = new QMutexPool( TRUE, 73 );
    if ( ! qt_thread_mutexpool )
	qt_thread_mutexpool = new QMutexPool( FALSE, 127 );
}

/*! \internal
  Cleans up the QThread system.
*/
void QThread::cleanup()
{
    delete qt_global_mutexpool;
    delete qt_thread_mutexpool;
    qt_global_mutexpool = 0;
    qt_thread_mutexpool = 0;
}

/*!
    Ends the execution of the calling thread and wakes up any threads
    waiting for its termination.
*/
void QThread::exit()
{
    pthread_exit( 0 );
}

/*  \internal
    helper function to do thread sleeps, since usleep()/nanosleep()
    aren't reliable enough (in terms of behavior and availability)
*/
static void thread_sleep( struct timespec *ti )
{
    pthread_mutex_t mtx;
    pthread_cond_t cnd;

    pthread_mutex_init(&mtx, 0);
    pthread_cond_init(&cnd, 0);

    pthread_mutex_lock( &mtx );
    (void) pthread_cond_timedwait( &cnd, &mtx, ti );
    pthread_mutex_unlock( &mtx );

    pthread_cond_destroy( &cnd );
    pthread_mutex_destroy( &mtx );
}

/*!
    System independent sleep. This causes the current thread to sleep
    for \a secs seconds.
*/
void QThread::sleep( unsigned long secs )
{
    struct timeval tv;
    gettimeofday( &tv, 0 );
    struct timespec ti;
    ti.tv_sec = tv.tv_sec + secs;
    ti.tv_nsec = ( tv.tv_usec * 1000 );
    thread_sleep( &ti );
}

/*!
    System independent sleep. This causes the current thread to sleep
    for \a msecs milliseconds
*/
void QThread::msleep( unsigned long msecs )
{
    struct timeval tv;
    gettimeofday( &tv, 0 );
    struct timespec ti;

    ti.tv_nsec = ( tv.tv_usec + ( msecs % 1000 ) * 1000 ) * 1000;
    ti.tv_sec = tv.tv_sec + ( msecs / 1000 ) + ( ti.tv_nsec / 1000000000 );
    ti.tv_nsec %= 1000000000;
    thread_sleep( &ti );
}

/*!
    System independent sleep. This causes the current thread to sleep
    for \a usecs microseconds
*/
void QThread::usleep( unsigned long usecs )
{
    struct timeval tv;
    gettimeofday( &tv, 0 );
    struct timespec ti;

    ti.tv_nsec = ( tv.tv_usec + ( usecs % 1000000 ) ) * 1000;
    ti.tv_sec = tv.tv_sec + ( usecs / 1000000 ) + ( ti.tv_nsec / 1000000000 );
    ti.tv_nsec %= 1000000000;
    thread_sleep( &ti );
}

/*!
    Begins execution of the thread by calling run(), which should be
    reimplemented in a QThread subclass to contain your code.  The
    operating system will schedule the thread according to the \a
    priority argument.

    If you try to start a thread that is already running, this
    function will wait until the the thread has finished and then
    restart the thread.

    \sa Priority
*/
void QThread::start(Priority priority)
{
    QMutexLocker locker( d->mutex() );

    if ( d->running )
        pthread_cond_wait(&d->thread_done, &locker.mutex()->d->handle);
    d->running = TRUE;
    d->finished = FALSE;

    int ret;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

#if !defined(Q_OS_OPENBSD) && defined(_POSIX_THREAD_PRIORITY_SCHEDULING) && (_POSIX_THREAD_PRIORITY_SCHEDULING-0 >= 0)
    switch (priority) {
    case InheritPriority:
	{
	    pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
	    break;
	}

    default:
	{
	    int sched_policy;
	    if (pthread_attr_getschedpolicy(&attr, &sched_policy) != 0) {
                // failed to get the scheduling policy, don't bother
                // setting the priority
                qWarning("QThread: cannot determine default scheduler policy");
                break;
	    }

	    int prio_min = sched_get_priority_min(sched_policy);
	    int prio_max = sched_get_priority_max(sched_policy);
            if (prio_min == -1 || prio_max == -1) {
                // failed to get the scheduling parameters, don't
                // bother setting the priority
                qWarning("QThread: cannot determine scheduler priority range");
                break;
            }

	    int prio;
	    switch (priority) {
	    case IdlePriority:
		prio = prio_min;
		break;

	    case HighestPriority:
		prio = prio_max;
		break;

	    default:
		// crudely scale our priority enum values to the prio_min/prio_max
		prio = (((prio_max - prio_min) / TimeCriticalPriority) *
			priority) + prio_min;
		prio = QMAX(prio_min, QMIN(prio_max, prio));
		break;
	    }

	    sched_param sp;
	    sp.sched_priority = prio;

	    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
	    pthread_attr_setschedparam(&attr, &sp);
	    break;
	}
    }
#endif // _POSIX_THREAD_PRIORITY_SCHEDULING

    if ( d->stacksize > 0 ) {
#if defined(_POSIX_THREAD_ATTR_STACKSIZE) && (_POSIX_THREAD_ATTR_STACKSIZE-0 > 0)
	ret = pthread_attr_setstacksize( &attr, d->stacksize );
#else
	ret = ENOSYS; // stack size not supported, automatically fail
#endif // _POSIX_THREAD_ATTR_STACKSIZE

	if ( ret ) {
#ifdef QT_CHECK_STATE
	    qWarning( "QThread::start: thread stack size error: %s", strerror( ret ) ) ;
#endif // QT_CHECK_STATE

	    // we failed to set the stacksize, and as the documentation states,
	    // the thread will fail to run...
	    d->running = FALSE;
	    d->finished = FALSE;
	    return;
	}
    }

    d->args[0] = this;
    d->args[1] = d;
#if defined(QT_USE_GLIBMAINLOOP)
    // The correct thread_id is set in QThreadInstance::start using the value of d->args[1]
    d->thread_id = NULL;

    // Legacy glib versions require this threading system initialization call
    if (!GLIB_CHECK_VERSION (2, 32, 0)) {
      if( ! g_thread_get_initialized () ) {
        g_thread_init(NULL);
      }
    }

    GThread* glib_thread_handle = g_thread_create((GThreadFunc)QThreadInstance::start, d->args, false, NULL);
    if (glib_thread_handle) {
	ret = 0;
    }
    else {
	ret = -1;
    }
#else // QT_USE_GLIBMAINLOOP
    ret = pthread_create( &d->thread_id, &attr, (QtThreadCallback)QThreadInstance::start, d->args );
#if defined (Q_OS_HPUX)
    if (ret == EPERM) {
        pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
	ret = pthread_create(&d->thread_id, &attr, (QtThreadCallback)QThreadInstance::start, d->args);
    }
#endif
    pthread_attr_destroy( &attr );
#endif // QT_USE_GLIBMAINLOOP

    if ( ret ) {
#ifdef QT_CHECK_STATE
	qWarning( "QThread::start: thread creation error: %s", strerror( ret ) );
#endif // QT_CHECK_STATE

	d->running = FALSE;
	d->finished = FALSE;
	d->args[0] = d->args[1] = 0;
    }
}

void QThread::start()
{
    start(InheritPriority);
}

/*!
    A thread calling this function will block until either of these
    conditions is met:

    \list
    \i The thread associated with this QThread object has finished
       execution (i.e. when it returns from \l{run()}). This function
       will return TRUE if the thread has finished. It also returns
       TRUE if the thread has not been started yet.
    \i \a time milliseconds has elapsed. If \a time is ULONG_MAX (the
    	default), then the wait will never timeout (the thread must
	return from \l{run()}). This function will return FALSE if the
	wait timed out.
    \endlist

    This provides similar functionality to the POSIX \c pthread_join() function.
*/
bool QThread::wait( unsigned long time )
{
    QMutexLocker locker( d->mutex() );

    if ( d->thread_id == pthread_self() ) {
#ifdef QT_CHECK_STATE
	qWarning( "QThread::wait: thread tried to wait on itself" );
#endif // QT_CHECK_STATE

	return FALSE;
    }

    if ( d->finished || ! d->running ) {
	return TRUE;
    }

    int ret;
    if (time != ULONG_MAX) {
	struct timeval tv;
	gettimeofday(&tv, 0);

	timespec ti;
	ti.tv_nsec = (tv.tv_usec + (time % 1000) * 1000) * 1000;
	ti.tv_sec = tv.tv_sec + (time / 1000) + (ti.tv_nsec / 1000000000);
	ti.tv_nsec %= 1000000000;

	ret = pthread_cond_timedwait(&d->thread_done, &locker.mutex()->d->handle, &ti);
    }
    else {
	ret = pthread_cond_wait(&d->thread_done, &locker.mutex()->d->handle);
    }

#ifdef QT_CHECK_RANGE
    if (ret && ret != ETIMEDOUT) {
	qWarning("Wait condition wait failure: %s",strerror(ret));
    }
#endif

    return (ret == 0);
}

/*!
    Returns the current cleanup behaviour of the thread.

    \sa setCleanupType
    \sa CleanupType
*/

QThread::CleanupType QThread::cleanupType() const {
    return (QThread::CleanupType)d->cleanupType;
}

/*!
    Sets the current cleanup behaviour of the thread.  The default,
    QThread::CleanupMergeObjects, will merge any objects owned by this thread
    with the main GUI thread when this thread is terminated.

    If faster thread termination performance is desired, QThread::CleanupNone
    may be specified instead.  However, this is not recommended as any objects
    owned by this thread on termination can then cause events to become "stuck"
    in the global event queue, leading to high CPU usage and other undesirable
    behavior.  You have been warned!

    \sa cleanupType
    \sa CleanupType
*/

void QThread::setCleanupType(CleanupType type) {
    d->cleanupType = type;
}

/*!
    Returns a pointer to the currently executing QThread.  If the
    current thread was not started using the QThread API, this
    function returns zero.

    Note that QApplication creates a QThread object to represent the
    main thread; calling this function from main() after creating
    QApplication will return a valid pointer.
*/
QThread *QThread::currentThreadObject()
{
    pthread_once(&storage_key_once, create_storage_key);
    return reinterpret_cast<QThread *>(pthread_getspecific(storage_key));
}


#endif // QT_THREAD_SUPPORT