pantheraleo
pantheraleo

Reputation: 23

Multi threading in c synchronization

I am trying read the array limit and numbers and trying to find out the sum of half numbers using first thread and sum of other half of the array using thread 2 but thread 2 is running right after reading limit if array using thread 1

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

 void *method(void *);
 int a[10];

 int main(){
   int error;
   pthread_t id1,id2;
   pthread_attr_t attr1,attr2;
   pthread_attr_init(&attr1);
   pthread_attr_init(&attr2);
   error = pthread_create(&id1,&attr1,method,(int *)0);
   error = pthread_create(&id2,&attr2,method,(int *)1);
   //wait();
   error = pthread_join(id1,NULL);
   if(error!=0){
     printf("\n Error in Joining 1");
   }
   wait();
   error = pthread_join(id2,NULL);
   if(error!=0){
     printf("\n Error in Joining 2");
   }
   return 0;
 }

 void *method(void *args){
   int ch = (int *)args;
   int i,n,sum=0;
   if(ch==0) {
     printf("\nEnter the limit : ");
     scanf("%d",&n);
     printf("\nEnter the Numbers : ");
     for (i = 0; i < n; i++) {
       scanf("%d",&a[i]);
     }
     for (i = 0; i < n/2; i++) {
       sum+=a[i];
     }
     printf("\nThe sum of first n/2 elements : %d",sum);
   } else {
     sum = 0;
     for (i = (n/2)+1; i < n; i++) {
       sum+=a[i];
     }
     printf("\nThe sum of first n elements : %d",sum);   
   }    
 }

Output from compiling/running:

[leox@leox ~/nos_lab $ gcc multi.c -lpthread
multi.c: In function ‘method’:
multi.c:27:12: warning: initialization makes integer from pointer without a cast [enabled by default]
   int ch = (int *)args;
        ^
leox@leox ~/nos_lab $ ./a.out
The sum of first n elements : 0
Enter the limit : 

ScreenShot

Upvotes: 1

Views: 104

Answers (1)

The Dark
The Dark

Reputation: 8514

If you don't want thread 2 to start until after thread 1 is finished, the simplest fix is to move the pthread_create for thread 2 to after the pthread_join for thread 1.

However, you still have a problem, because n and sum are local variables to method and the two threads will call method separately. You could move these variables out to be global as you have with a, or you could set up a structure to be passed as a pointer to the method thread function that contains the data you want to use/update.

Also note that making one thread wait until the other thread is completely finished removes any performance improvements you might gain from threading.

Upvotes: 1

Related Questions