POSIX: Difference between revisions

From miki
Jump to navigation Jump to search
Line 10: Line 10:
* [http://en.wikipedia.org/wiki/POSIX_Threads POSIX Threads] (wikipedia)
* [http://en.wikipedia.org/wiki/POSIX_Threads POSIX Threads] (wikipedia)


Manual page:
;Advices
* [http://localhost/cgi-bin/dwww?type=runman&location=pthreads/7 pthreads (7)]
* For portability, always create ''joinable'' or ''detachable'' threads by setting explicitly the thread attribute (using <code>pthread_attr_getdetachstate</code>). This provides portability as not all implementations may create threads as joinable by default.

=== Portability ===
; Joinable / detachable state
: For portability, always create ''joinable'' or ''detachable'' threads by setting explicitly the thread attribute (using <code>pthread_attr_getdetachstate</code>). This provides portability as not all implementations may create threads as joinable by default.


=== Thread-Local Data ===
=== Thread-Local Data ===

Revision as of 22:48, 3 November 2012

PThreads

General Information

Links:

Manual page:

Portability

Joinable / detachable state
For portability, always create joinable or detachable threads by setting explicitly the thread attribute (using pthread_attr_getdetachstate). This provides portability as not all implementations may create threads as joinable by default.

Thread-Local Data

// Compile this code with : gcc local.c -o local -lpthread

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

static __thread int myint;
static int globalint = 0;

void * handler(void *arg)
{
    myint = ++globalint;                              // thread unsafe - should use a mutex
    while(1) {
        printf("myint is %d\n", myint);
        sleep(1);
    }
}

int main (int argc, char **argv)
{
    pthread_t p1,p2;

    pthread_create(&p1, NULL, handler, NULL);
    pthread_create(&p2, NULL, handler, NULL);

    pause();
    return 0;
}

Debugging

See Debugging page.