Created
September 29, 2016 14:18
-
-
Save kotaroito/22d882426ee108e4ec09e0e743458e25 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 <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
int x = 0; | |
int n = 100; | |
pthread_t tid[100]; | |
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; | |
void* calc() | |
{ | |
int j = 0; | |
for (j = 0; j < 10000000; j++) { | |
pthread_mutex_lock(&mut); | |
x = x + 1; | |
x = x - 1; | |
pthread_mutex_unlock(&mut); | |
} | |
return ((void *)0); | |
} | |
int main() | |
{ | |
int i = 0; | |
int err; | |
for (i = 0; i < n; i++) { | |
err = pthread_create(&(tid[i]), NULL, &calc, NULL); | |
if (err != 0) | |
printf("\ncan't create thread :[%s]", strerror(err)); | |
} | |
for (i = 0; i < n; i++) { | |
err = pthread_join(tid[i], NULL); | |
if (err != 0) | |
printf("\ncan't join with thread :[%s]", strerror(err)); | |
} | |
printf("x is %d\n", x); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment