Question

I want to increase one number using threads.I have this code :

#include <pthread.h>
int S;
pthread_t t;
suma(){
  S++;
}
main(){
int i;
for(i=1;i<=20000;i++)
  pthread_create(&t,NULL,suma,NULL)
pthread_join(s,NULL);
printf("%d",S);
}

The result would not be 20000( I know the reason). I've tried to use mutex threads but i am not so sure if i use this threads right :

Code with mutex:

#include <pthread.h>
int S;
pthread_t t;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
suma(){
  pthread_mutex_lock(&lock);
  S++;
  pthread_mutex_unlock(&lock);
}
main(){
int i;
for(i=1;i<=20000;i++)
  pthread_create(&t,NULL,suma,NULL)
pthread_join(s,NULL);
printf("%d",S);
}

I've think that i need some test in suma() to work properly, but i don't know how to do this.

Was it helpful?

Solution

You need join every thread you created, so you can't reuse the same pthread_t variable, and 20000 threads may be too many.

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

int S = 0;
pthread_t t[201];
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

suma(){
    pthread_mutex_lock(&lock);
    S++;
    pthread_mutex_unlock(&lock);
}

int main(){
    int i;
    for(i=1;i<=200;i++)
        pthread_create(&t[i],NULL,suma,NULL);

    for(i=1;i<=200;i++)
        pthread_join(t[i],NULL);
    printf("%d",S);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top