Syncronization in threads using POSIX thread

Advertisements

Thread Synchronization is an important part of Operating System.It is explaining that concurrently-executing threads or processes do not execute specific portions of a program at the same time. If one thread has begun to execute a serialized portion of the program, any other thread trying to execute this portion must wait until the first thread finishes.

Generally the serialize portion of the program is called a s critical section,means if a thread is running in its critical section means no other thread are allowed to enter into their critical section. There are different technique of process/thread synchronization available in C++

  • Locking

  • Mutex

  • Monitor (synchronization)

  • Semaphore

Here is a mutex method of thread Synchronization example using C++

//thread synchronization
#include 
#include 
#include 
#include 
#include 
using namespace std;
pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;

void *writer1(void *fd)
{
   int f=*(int*)fd;
   char *string1=new char[200];
   pthread_mutex_lock(&m);
   cout<<"\n enter 1st thread items to write in file";
   gets(string1);
   for(int i=0;i<=strlen(string1);i++)
   {
      write(f,&string1[i],1);
      sleep(1);
   }
   pthread_mutex_unlock(&m);
}
void *writer2(void *fd)
{
   int f=*(int*)fd;
   char *string2=new char[200];
   pthread_mutex_lock(&m);
   cout<<"\n enter enter second thread items to write in file";
   gets(string2);
   for(int i=0;i<=strlen(string2);i++)
   {
      write(f,&string2[i],1);
      sleep(1);
   }
   pthread_mutex_unlock(&m);
}
main()
{
   pthread_t t1,t2;
   int fd=open("file.txt",O_CREAT|O_RDWR|O_APPEND);
   pthread_create(&t1,0,writer1,&fd);
   pthread_create(&t2,0,writer2,&fd);
   pthread_join(t1,0);
   pthread_join(t2,0);
}

About SourceCode

  • pthread_create(),pthread_join() are two library function to create thread and waiting for thread simultaneously.

  • pthread_mutex_t is used to declare mutex variable.

  • PTHREAD_MUTEX_INITIALIZER is used to initialize a static mutex.

  • Here we are doing file locking using pthread_mutex_lock(pthread_mutex_t*) function and unlocking using pthread_mutex_unlock(pthread_mutex_t*) function.

  • The primary objective of this source code is to write into a file in a synchronization way.

Application Area

  • Banking Transaction

  • Database System

  • Web Servers

  • Designing Multithreading OS

Mohtashim

Mohtashim

Blend of technical and managerial skill with overall 15 of experience in Telecom and Data communication domain with design, development, implementation & supporting complex Business Support Systems (BSS) and Operation Support Systems (OSS).
Mohtashim
Mohtashim

Latest posts by Mohtashim (see all)

Advertisements