|
CS471/571 - Operating Systems
|
Displaying ./code/Pthreads/p2.c
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NT 4
// gcc -o p2 p2.c -lpthread
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;
void *thread_main(int *tid)
{
for(int i=0; i < 1000000; i++) {
pthread_mutex_lock(&lock);
sum = sum + 1;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void)
{
pthread_t thread_handle[NT];
int thread_id[NT];
printf("parent thread id = %d, process id = %d\n", gettid(), getpid());
// Launch the NT number of threads:
for(int i=0; i < NT; i++) {
thread_id[i] = i;
pthread_create(&thread_handle[i], NULL, (void *)thread_main, &thread_id[i]);
}
// Wait for the threads to complete:
for(int i=0; i < NT; i++) {
pthread_join(thread_handle[i], NULL);
}
printf("sum = %d\n", sum);
return 0;
}
|