matheus__serpa icon

pthread_example

matheus__serpa | PRO | 09/20/17 10:49:55 PM UTC | 0 ⭐ | 435 👁️ | Never ⏰ | []
C |

1.52 KB

|

None

|

0 👍

/

0 👎

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
 
long int MAX;
long int sum = 0;
long int n_threads;
pthread_mutex_t lock;
 
void* somador(void *tid){
    long int i, start, end, sum_local = 0;
    long int *id = (long int *) tid;
 
    start = *id * (MAX / n_threads);
    if(*id == n_threads - 1)
        end = MAX;
    else
        end = start + (MAX / n_threads);
    
    for(i = start; i < end; i++)
        sum_local++;
 
    printf("thread %ld - sum = %ld\n", *id, sum_local);
 
    pthread_mutex_lock(&lock);
    sum += sum_local;
    pthread_mutex_unlock(&lock);
 
 
    pthread_exit(NULL);
}
 
int main(int argc, char ** argv) {
    if(argc != 3){
        fprintf(stderr, "Usage: %s <n_threads> <max>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    n_threads = atoi(argv[1]);
    MAX = atoi(argv[2]);
 
    long int tid;
    pthread_t *threads;
    struct timespec start, finish;
    double elapsed;
 
    threads = (pthread_t *) malloc(n_threads * sizeof(pthread_t));
 
    pthread_mutex_init(&lock, NULL);
 
    clock_gettime(CLOCK_MONOTONIC, &start);
 
    for(tid = 0; tid < n_threads; tid++)
        pthread_create(&threads[tid], NULL, (void *) somador, (void *) &tid);
 
    for(tid = 0; tid < n_threads; tid++)
        pthread_join(threads[tid], NULL);
 
    pthread_mutex_destroy(&lock);
    
    clock_gettime(CLOCK_MONOTONIC, &finish);
    elapsed = (finish.tv_sec - start.tv_sec) + (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
 
    printf("\nTotal time: %.10f seconds\n\n", elapsed);
 
    printf("sum global = %ld\n", sum);
 
    free(threads);
 
    pthread_exit(NULL);
}

Comments