Friday, October 21, 2011

Implement semaphore in C.

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

void* thread_a( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp = fopen ("thread_a.txt", "w+");
    fprintf(fp,"%s","thread_a");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_b( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_b.txt", "w+");
    fprintf(fp,"%s","thread_b");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_c( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_c.txt", "w+");
    fprintf(fp,"%s","thread_c");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

int main()
{
    pthread_mutex_t mtx;
    pthread_t tA;
    pthread_t tB;
    pthread_t tC;
    pthread_mutex_init( &mtx, NULL );
    pthread_create( &tA, NULL, &thread_a, &mtx );
    pthread_join( tA, NULL );  /* wait for the thread_a to finish */
    pthread_create( &tB, NULL, &thread_b, &mtx );
    pthread_join( tB, NULL );  /* wait for the thread_b to finish */
    pthread_create( &tC, NULL, &thread_c, &mtx );
    pthread_join( tC, NULL );  /* wait for the thread_c to finish */
   
    return 0;
}

No comments :