Friday, July 20, 2012

Thread Handling Example in C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <pthread.h>  
 #include <stdlib.h>  
 #include <signal.h>  
   
   
 #define ARRAYSIZE 1000  
 #define THREADS 10  
   
 void *slave(void *myid);  
   
   
 /* shared data */  
 int data[ARRAYSIZE]; /* Array of numbers to sum */  
 int sum = 0;  
 pthread_mutex_t mutex; /* mutually exclusive lock variable */  
 //int wsize;     /* size of work for each thread */   
 /* end of shared data */  
 FILE *file;  
 char filename[25];  
   
 pthread_t tid[THREADS];  
 int wsize = ARRAYSIZE/THREADS;   
 int k=1;  
   
 void pwrproc(int s)  
 {  
 k=0;  
   
 }  
   
   
   
 void *slave(void *myid)  
 {  
 int i,low,high,myresult=0;  
 printf("thread %u is created.\n",(unsigned int)pthread_self());  
 while(k) sleep(5);  
 printf("thread %u has recieved signal.\n",(unsigned int)pthread_self());  
 low=(int)myid*wsize;  
 high = low + wsize;  
   
   for (i=low;i<high;i++)  
       myresult += data[i];  
   
 fprintf(file,"The sum from %d to %d is %d \n",low,high,myresult);  
 pthread_mutex_lock(&mutex);  
 sum += myresult;  
 pthread_mutex_unlock(&mutex);  
   
 return myid;  
 }  
   
 main()  
 {  
   
   int i=0;  
   signal(SIGPWR,pwrproc);  
   
   fprintf(stdout, "Enter the File Name: ");  
   fscanf(stdin,"%s",filename);  
   file= fopen(filename,"w");  
   fprintf(file,"The process ID is %d\n",getpid());  
   fprintf(file,"The Parent Process ID is %d\n\n",getppid());  
   //fclose(file);  
   
   printf("The process ID is %d\n",getpid());  
   printf("The Parent Process ID is %d\n",getppid());  
   pthread_mutex_init(&mutex,NULL); /* initialize mutex */  
   
    /* wsize must be an integer */  
   
     for(i=0;i<ARRAYSIZE;i++)    /* initialize data[] */  
       data[i] = i+1;  
   
     
    for (i=0;i<THREADS;i++) /* create threads */  
       if (pthread_create(&tid[i],NULL,slave,(void *)i) != 0)  
          perror("Pthread_create fails");  
   
    for (i=0;i<THREADS;i++) /* join threads */  
       if (pthread_join(tid[i],NULL) != 0)  
          perror("Pthread_join fails");  
     
    printf("The sum from 1 to %i is %d\n",ARRAYSIZE,sum);  
   
   printf("The Signal is reached. Data is saved in - %s\n",filename);  
   
 }  

1 comments: