I am trying to write a simple program to understand threads. I want each thread to increment a global variable 'counter' to 4 million. Each thread only counts to 2 million. I placed a print statement at the end of each function to see how many iterations and where the global counter is at upon completion of the function. But the global counter in thread1Func is always very high, like 3.8 - 3.9 million, and then in thread2Func the counter is always 4 mil (as expected).
Am I doing this correctly? Is there a reason thread1Func is always printing such a high value for 'counter'? I would imagine it should be somewhere between 2 mil - 4 mil more evenly. Any advice would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define MAX 2000000UL
pthread_mutex_t lock;
//pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct shared_data
{
int value; /* shared variable to store result*/
};
struct shared_data *counter;
void* thread1Func(void * tid){
uint32_t i = 0;
while(i < MAX){
if(pthread_mutex_trylock(&lock) == 0){
counter->value++;
pthread_mutex_unlock(&lock);
i++;
}
}
printf("I am thread 1. I counted %d times. Global counter = %d\n", i, counter->value);
return NULL;
}
void* thread2Func(void * tid){
uint32_t i = 0;
while(i < MAX){
if(pthread_mutex_trylock(&lock) == 0){
counter->value++;
pthread_mutex_unlock(&lock);
i++;
}
}
printf("I am thread 2. I counted %d times. Global counter = %d\n", i, counter->value);
return NULL;
}
int main() {
counter = (struct shared_data *) malloc(sizeof(struct shared_data));
printf("Initial Counter Value: %d\n", counter->value);
pthread_t thread1;
pthread_t thread2;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, thread1Func, NULL);
pthread_create(&thread2, NULL, thread2Func, NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("Final Counter: %d\n", counter->value);
return 0;
}