#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int myglobal;
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
int do_work(void)
{
int i, sum;
sum = 0;
for (i = 0; i < 100000; i++) sum = sum + i;
return sum;
}
void *thread_function(void *arg)
{
int i,j;
for (i=0; i < 1000; i++) {
pthread_mutex_lock(&mymutex);
j = myglobal;
j = j + 1;
do_work();
myglobal = j;
pthread_mutex_unlock(&mymutex);
do_work();
}
return NULL;
}
int main(void)
{
pthread_t mythread;
int i;
myglobal = 0;
if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
printf("error creating thread.");
abort();
}
for ( i=0; i < 1000; i++) {
pthread_mutex_lock(&mymutex);
myglobal = myglobal + 1;
pthread_mutex_unlock(&mymutex);
do_work();
}
if ( pthread_join ( mythread, NULL ) ) {
printf("error joining thread.");
abort();
}
printf("myglobal equals %d\n",myglobal);
exit(0);
}