Chinaunix首页 | 论坛 | 博客
  • 博客访问: 107240
  • 博文数量: 21
  • 博客积分: 85
  • 博客等级: 民兵
  • 技术积分: 364
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-08 00:28
文章分类

全部博文(21)

文章存档

2013年(1)

2012年(7)

2011年(13)

分类:

2011-12-08 00:29:31

多个线程对同一变量读写,如果不做同步处理,数据可能不一致

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <time.h>
  4. static int count=0;
  5. void *test1()
  6. {
  7.     printf("pthread 1\n");
  8.     int i=0;
  9.     while(i++!=11111110) //如果数据太小在线程让出cpu之前就已经完成操作,就看不到不一致的效果鸟~~
  10.     {
  11.         count++;
  12.         }
  13.     return NULL;
  14. }

  15. void *test2()
  16. {
  17.     printf("pthread 2\n");
  18.     int i=0;
  19.     while(i++!=11111160)
  20.     {
  21.         count++;
  22.         }
  23.     return NULL;
  24. }

  25. int main()
  26. {
  27.     pthread_t a,b;
  28.     pthread_create(&a,NULL,test1,NULL); //创建新线程,默认线程属性
  29.     pthread_create(&b,NULL,test2,NULL);
  30.     sleep(2);
  31.     printf("%d\n",count);
  32. }
运行结果:
  1. coder@coder:~/C and C++/pthread$ ./a.out
  2. pthread 1
  3. pthread 2
  4. 14280152
  5. coder@coder:~/C and C++/pthread$ ./a.out
  6. pthread 1
  7. pthread 2
  8. 15333212
  9. coder@coder:~/C and C++/pthread$ ./a.out
  10. pthread 1
  11. pthread 2
  12. 13588147
使用互斥量保证只有一个线程在读写变量,在它完成工作之前,其他线程只能等待
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <time.h>
  4. static int count=0;
  5. pthread_mutex_t p_lock;                            //定义互斥量
  6. void *test1()
  7. {
  8.     pthread_mutex_lock(&p_lock); //加锁 ,如果被其他线程抢先一步,就阻塞等待
  9.     printf("pthread 1\n");
  10.     int i=0;
  11.     while(i++ != 11111110)
  12.     {
  13.         count++;
  14.     }
  15.     pthread_mutex_unlock(&p_lock); //解锁
  16.     return NULL;
  17. }

  18. void *test2()
  19. {
  20.     pthread_mutex_lock(&p_lock);
  21.     printf("pthread 2\n");
  22.     int i=0;
  23.     while(i++ != 11111160)
  24.     {
  25.         count++;
  26.     }
  27.     pthread_mutex_unlock(&p_lock);
  28.     return NULL;
  29. }

  30. int main()
  31. {
  32.     pthread_t a,b;
  33.     pthread_mutex_init(&p_lock,NULL);                //使用默认属性初始化互斥量
  34.     if(pthread_create(&a,NULL,test1,NULL)!=0) //创建新线程,默认线程属性
  35.     {
  36.         printf("can‘t create thread\n");
  37.     }
  38.     if(pthread_create(&b,NULL,test2,NULL)!=0)
  39.     {
  40.         printf("can‘t create thread\n");
  41.     }
  42.     pthread_mutex_destroy(&p_lock);                  //销毁
  43.     sleep(2);
  44.     printf("%d\n",count);
  45.     }
运行结果:
  1. coder@coder:~/C and C++/pthread$ ./a.out
  2. pthread 1
  3. pthread 2
  4. 22222270
  5. coder@coder:~/C and C++/pthread$ ./a.out
  6. pthread 1
  7. pthread 2
  8. 22222270
  9. coder@coder:~/C and C++/pthread$ ./a.out
  10. pthread 1
  11. pthread 2
  12. 22222270

gcc pthread.c -lphtread

阅读(1029) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~