pthreadとmutex

戻る
::::::::::::::
Mutex-test.c
::::::::::::::
#include <pthread.h>
#include <errno.h>
#include <stdio.h>

#define NUM_CHAIRS   1
#define NUM_MEMBERS  10

/**
* $Id: mutex.html,v 1.1 2009/06/22 16:12:18 kishi Exp kishi $
*/

typedef struct {
    pthread_t id;
    int member_id;
}
thread_data;

int counter = 0;
pthread_mutex_t mutex;

void
critical_section ( void ) {
    counter++;
}

void *
function ( void *p ) {
    thread_data * td = p;
    struct timespec abs_time;

    abs_time.tv_sec = time ( NULL ) + 0;
    abs_time.tv_nsec = 0;

    //-------------------------------------------------------
    // sleep time varies by each thread
    //-------------------------------------------------------
    sleep( 1 + td->member_id % 3 );

    pthread_mutex_lock( &mutex );
    critical_section ();
    printf( "memebr_id = %d: counter=%d\n", td->member_id, counter );
    pthread_mutex_unlock( &mutex );

    return 0;
}

int
main ( void ) {
    int i;
    thread_data data[ NUM_MEMBERS ];

    for ( i = 0; i < NUM_MEMBERS; i++ ) {
        data[ i ].member_id = i;

        if ( pthread_create ( &data[ i ].id, 0, function, &data[ i ] ) != 0 ) {
            printf ( "cannot create thread: %d.\n", errno );
        }
    }

    for ( i = 0; i < NUM_MEMBERS; i++ ) {
        if ( 0 != pthread_join ( data[ i ].id, 0 ) ) {
            printf ( "Cannot join thread %d: %d.\n", i, errno );
        }
    }

    return 0;
}

■実行結果

$ ./Mutex-test.exe
memebr_id = 3: counter=1
memebr_id = 6: counter=2
memebr_id = 9: counter=3
memebr_id = 0: counter=4
memebr_id = 1: counter=5
memebr_id = 4: counter=6
memebr_id = 7: counter=7
memebr_id = 2: counter=8
memebr_id = 5: counter=9
memebr_id = 8: counter=10

戻る

inserted by FC2 system