クリティカルセクションとマルチスレッド

戻る

#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <stdio.h>

#define NUM_CHAIRS   1
#define NUM_MEMBERS  10

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

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

sem_t semaphore;
int counter = 0;

void
critical_section ( void ) {
    counter++;
}

void *
member_thread ( 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 );

    if ( 0 == sem_timedwait ( &semaphore, &abs_time ) ) {

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

    } else {
        fprintf( stderr, "cannot interrupt!\n" );
    }

    return 0;
}

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

    sem_init ( &semaphore, 0, NUM_CHAIRS );

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

        if ( pthread_create ( &data[ i ].id, 0, member_thread, &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 );
        }
    }

    sem_destroy ( &semaphore );

    return 0;
}

戻る

inserted by FC2 system