+ -
当前位置:首页 → 问答吧 → 求助:是否安全的volatile变量?

求助:是否安全的volatile变量?

时间:2010-08-03

来源:互联网

volatile int count;

如果A线程只是访问该变量,

B线程会修改变量;

有问题吗?我感觉没问题。

望大家指导,谢谢。

作者: okocha-jay   发布时间: 2010-08-03

SB的linux,shit

没问题啊,你不放心就加锁。

作者: 梅川内依酷   发布时间: 2010-08-03

本帖最后由 okocha-jay 于 2010-08-03 18:48 编辑

谢谢。做了个测试代码。暂时没问题
有错误,还需再改。
  1. #include <stdio.h>
  2. #include <pthread.h>

  3. #define N 100000

  4. int a[N] = {0};
  5. volatile int r = 0; // index to a
  6. volatile int w = 0; // index to a

  7. #define NotFull (w <= N - 1)

  8. #define NotEmpty (r < w)
  9. // w 是由生产者修改, 消费者要访问的
  10. void * Pthread(void *arg) // 生产者
  11. {
  12.         printf("producer %u\n", pthread_self());
  13.         while ( NotFull )
  14.         {
  15.                 usleep(1);
  16.                 a[w] = w; // 模仿Stevens的进程间通信书中例子
  17.                 ++w;
  18.         }
  19.         return 0;
  20. }

  21. void * Cthread(void *arg) // 消费者
  22. {
  23.         printf("consumer %u\n", pthread_self());
  24.         while ( NotEmpty || NotFull )
  25.         {
  26.                                 usleep(1);
  27.                 if ( !NotEmpty)//消费的太快了
  28.                          continue;
  29.                                     
  30.                                 if ( r != a[r] )

  31.                         printf("ERROR : a[%d] = %d\n", r, a[r]);
  32.                                 ++ r;
  33.         }
  34. }
  35. int main()
  36. {
  37.         pthread_t prod, con;

  38.         pthread_create(&prod, NULL, Pthread, NULL);
  39.         pthread_create(&con, NULL, Cthread, NULL);

  40.         pthread_join(prod, NULL) ;
  41.         pthread_join(con, NULL) ;
  42.        
  43.         return 0;
  44. }
复制代码

作者: okocha-jay   发布时间: 2010-08-03

volatile 变量阿,如果你对访问变量的正确性不是很高要求的话,这样做应该没问题。

作者: davelv   发布时间: 2010-08-03

相关阅读 更多