Created
July 25, 2019 03:53
-
-
Save surinoel/f83954c94238d902e4c753bfc8770c42 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
long long sum = 0; | |
pthread_mutex_t mutex; | |
void *thread_main(void *arg) | |
{ | |
int start = ((int *)arg)[0]; | |
int end = ((int *)arg)[1]; | |
for(int i=start; i<=end; i++) { | |
pthread_mutex_lock(&mutex); | |
sum += i; | |
pthread_mutex_unlock(&mutex); | |
} | |
return NULL; | |
} | |
int main(int argc, char **argv) | |
{ | |
pthread_t tid1, tid2; | |
int range1[2] = { 1, 10000000}; | |
int range2[2] = { 10000001, 20000000 }; | |
if(pthread_mutex_init(&mutex, NULL) != 0) { | |
perror("pthread mutex init"); | |
return -1; | |
} | |
if(pthread_create(&tid1, NULL, thread_main, (void *)range1) != 0) { | |
perror("pthread create 1"); | |
return -1; | |
} | |
if(pthread_create(&tid2, NULL, thread_main, (void *)range2) != 0) { | |
perror("pthread create 2"); | |
return -1; | |
} | |
if(pthread_join(tid1, NULL) < 0) { | |
perror("pthread join 1"); | |
return -1; | |
} | |
if(pthread_join(tid2, NULL) < 0) { | |
perror("pthread join 2"); | |
return -1; | |
} | |
printf("sum = %lld\n", sum); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment