Last active
December 31, 2015 05:30
-
-
Save yudi-matsuzake/3789425deb869ed767cc to your computer and use it in GitHub Desktop.
Example of mutual exclusion problem in POSIX threads
This file contains 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
// Mutual Exclusion Example | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#define NUM_THREADS 500 | |
#define N_SUM 100000 | |
void* sum(void *t) | |
{ | |
long* n = (long*)t; | |
int i; | |
for (i=0; i<N_SUM ; i++) | |
{ | |
(*n)++; | |
} | |
pthread_exit((void*) t); | |
} | |
int main () | |
{ | |
printf("Number of threads: %d\nEvery thread will sum %d times.\n", NUM_THREADS, N_SUM); | |
pthread_t thread[NUM_THREADS]; | |
pthread_attr_t attr; | |
int rc; | |
// variable that will be access for every thread | |
long n = 0; | |
void *status; | |
/* Initialize and set thread detached attribute */ | |
pthread_attr_init(&attr); | |
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); | |
long t; | |
for(t=0; t<NUM_THREADS; t++) { | |
rc = pthread_create(&thread[t], &attr, sum, (void *)&n); | |
} | |
/* Free attribute and wait for the other threads */ | |
pthread_attr_destroy(&attr); | |
for(t=0; t<NUM_THREADS; t++) { | |
rc = pthread_join(thread[t], &status); | |
} | |
printf("Right value:\t%d;\nResult:\t\t%ld.\n", NUM_THREADS*N_SUM, n); | |
pthread_exit(NULL); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment