- #include <stdio.h>
-
#include <unistd.h>
-
#include <assert.h>
-
#include <pthread.h>
-
-
#define TIMES 1000
-
-
int num = 0;
-
-
pthread_mutex_t mutex;
-
-
void * do_add(void *args)
-
{
-
int i;
-
-
for(i = 0; i < TIMES; i ++)
-
{
-
pthread_mutex_lock(&mutex);
-
num ++;
-
pthread_mutex_unlock(&mutex);
-
printf("A");
-
}
-
return NULL;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
int ret;
-
pthread_t ptid[2];
-
-
pthread_mutex_init(&mutex, NULL);
-
-
ret = pthread_create(&ptid[1], NULL, do_add, NULL);
-
if(ret != 0)
-
{
-
printf("Error: create thread failed.\n");
-
}
-
-
ret = pthread_create(&ptid[1], NULL, do_add, NULL);
-
if(ret != 0)
-
{
-
printf("Error: create thread failed.\n");
-
}
-
-
pthread_join(ptid[0], NULL);
-
pthread_join(ptid[1], NULL);
-
pthread_mutex_destroy(&mutex);
-
-
printf("Num = %d\n", num);
-
return 0;
-
}
gcc sync.c -Wall -g -lpthread -o ap
- OS: Ubuntu 10.04
反复运行10次左右,总有两三次num的值不为2000.