Skip to content

Instantly share code, notes, and snippets.

@kotaroito
Created September 29, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotaroito/22d882426ee108e4ec09e0e743458e25 to your computer and use it in GitHub Desktop.
Save kotaroito/22d882426ee108e4ec09e0e743458e25 to your computer and use it in GitHub Desktop.
#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