- 论坛徽章:
- 0
|
我在运行《深入理解计算机系统》这本书“并发编程”这一章中的一个互斥锁的例子时,结果不对,请大牛给分析一下。
- #include<pthread.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<semaphore.h>
- #define NITERS 10000000
- void *count(void *arg);
- unsigned int cnt=0;
- sem_t mutex;
- int main()
- {
- sem_init(&mutex,0,1);
- pthread_t tid1,tid2;
- pthread_create(&tid1,NULL,count,NULL);
- pthread_create(&tid2,NULL,count,NULL);
- pthread_join(tid1,NULL);
- pthread_join(tid2,NULL);
- if(cnt != (unsigned)NITERS*2)
- printf("Boom! cn=%d \n",cnt);
- else
- printf("OK cnt=%d \n",cnt);
- exit(0);
- }
- void *count(void*arg)
- {
- int i;
- for(i=0;i<NITERS;i++)
- {
- sem_wait(&mutex);
- cnt++;
- sem_post(&mutex);
- }
- return NULL;
- }
复制代码
机器环境是MacOSX 10.4,编译器是gcc 4.0
[ 本帖最后由 wxs1024 于 2005-12-13 02:07 编辑 ] |
|