#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex_lock;
static volatile int count = 0;
void *test_func(void *arg)
{
int i = 0;
for(i = 0; i < 2000000; i++)
{
pthread_mutex_lock(&mutex_lock); // a thread should get this mutex lock first.
count++; // at one time, this grobal var can be accessed by only one thread which holds this mutex lock.
pthread_mutex_unlock(&mutex_lock); // after access, thread should release this lock.
}
return NULL;
}
int main(void)
{
pthread_mutex_init(&mutex_lock, NULL);
pthread_t thread_ids[10];
int i = 0;
for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)
{
pthread_create(&thread_ids[i], NULL, test_func, NULL);
}
for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)
{
pthread_join(thread_ids[i], NULL); // wait threads to exit.
}
printf("count: %d\n", count);
return 0;
}
the execution result:
count: 20000000 // 2000000 * 10(10 threads)