Using Mutex to implement atomicity

/***********************************************************************
* OBJECTIVE : Implement atomicity in case of threads
* FILE NAME : mutex.c
* DATE      : 10-09-2012
* AUTHOR    : Abhishek Kumar Singh
************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>

/* Gobal data */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

void *increment(void *);

int main()
{
    pthread_t thread1,thread2;
    int iret1,iret2;

    /* Create two threads that executes independently and parallely */
    iret1 = pthread_create(&thread1,NULL,increment,NULL);
    iret2 = pthread_create(&thread2,NULL,increment,NULL);

    if(iret1 != 0)
        fprintf(stderr,"thread1 can't created");
    if(iret2 != 0 )
        fprintf(stderr,"thread2 can't be created");

    /* Waiting for the threads to terminate */
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);

    return EXIT_SUCCESS;
}

void *increment(void *ptr)
{
    /* Locking Resources for other threads */
    pthread_mutex_lock(&mutex);
    counter ++;
    printf("counter:%d\n",counter);
    pthread_mutex_unlock(&mutex);
    /* Unlocking Resources so that other threads can acess */
    return NULL;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s