-
#include "stdio.h"
-
#include "string.h"
-
#include "pthread.h"
-
#include "unistd.h"
-
-
int counter;
-
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;/*定义并初始化互斥锁*/
-
-
void *update(void *vptr)
-
{
-
int i,val;
-
-
while(1)
-
{
-
pthread_mutex_lock(&counter_mutex);/*上锁*/
-
val = counter;
-
printf("%x: %d\n",(unsigned int)pthread_self(),val+1);
-
counter = val + 1;
-
pthread_mutex_unlock(&counter_mutex);/*开锁*/
-
sleep(1);
-
}
-
-
return NULL;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
pthread_t tha,thb;
-
-
pthread_create(&tha,NULL,&update,NULL);/*创建两个线程,调用同一个函数*/
-
pthread_create(&thb,NULL,&update,NULL);
-
-
pthread_join(tha,NULL);
-
pthread_join(thb,NULL);
-
-
return 0;
-
}
编 译:gcc -o mutex pthread_mutex.c -l pthread
运行结果:
b7f42b90: 1
b7541b90: 2
b7f42b90: 3
b7541b90: 4
b7f42b90: 5
b7541b90: 6
b7f42b90: 7
b7541b90: 8
。
。
。
Tips:
可以将lock和unlock两句注释掉,对比看下运行结果--
阅读(635) | 评论(0) | 转发(0) |