Chinaunix首页 | 论坛 | 博客
  • 博客访问: 17186
  • 博文数量: 14
  • 博客积分: 631
  • 博客等级: 上士
  • 技术积分: 115
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-10 22:53
文章分类
文章存档

2011年(2)

2010年(12)

我的朋友

分类: LINUX

2011-02-25 20:06:25

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <assert.h>
  4. #include <pthread.h>

  5. #define TIMES        1000

  6. int num = 0;

  7. pthread_mutex_t mutex;

  8. void * do_add(void *args)
  9. {
  10.     int i;

  11.     for(i = 0; i < TIMES; i ++)
  12.     {
  13.         pthread_mutex_lock(&mutex);
  14.         num ++;
  15.         pthread_mutex_unlock(&mutex);
  16.         printf("A");
  17.     }
  18.     return NULL;
  19. }

  20. int main(int argc, char *argv[])
  21. {
  22.     int ret;
  23.     pthread_t ptid[2];

  24.     pthread_mutex_init(&mutex, NULL);

  25.     ret = pthread_create(&ptid[1], NULL, do_add, NULL);
  26.     if(ret != 0)
  27.     {
  28.         printf("Error: create thread failed.\n");
  29.     }

  30.     ret = pthread_create(&ptid[1], NULL, do_add, NULL);
  31.     if(ret != 0)
  32.     {
  33.         printf("Error: create thread failed.\n");
  34.     }

  35.     pthread_join(ptid[0], NULL);
  36.     pthread_join(ptid[1], NULL);
  37.     pthread_mutex_destroy(&mutex);

  38.     printf("Num = %d\n", num);
  39.     return 0;
  40. }
gcc sync.c -Wall -g -lpthread -o ap
  1. OS: Ubuntu 10.04
反复运行10次左右,总有两三次num的值不为2000.
阅读(296) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:/dev/random与/dev/urandom

给主人留下些什么吧!~~