求助:是否安全的volatile变量?
时间:2010-08-03
来源:互联网
volatile int count;
如果A线程只是访问该变量,
B线程会修改变量;
有问题吗?我感觉没问题。
望大家指导,谢谢。
如果A线程只是访问该变量,
B线程会修改变量;
有问题吗?我感觉没问题。
望大家指导,谢谢。
作者: okocha-jay 发布时间: 2010-08-03
SB的linux,shit
没问题啊,你不放心就加锁。
没问题啊,你不放心就加锁。
作者: 梅川内依酷 发布时间: 2010-08-03
本帖最后由 okocha-jay 于 2010-08-03 18:48 编辑
谢谢。做了个测试代码。暂时没问题
有错误,还需再改。
复制代码
谢谢。做了个测试代码。暂时没问题
有错误,还需再改。
- #include <stdio.h>
- #include <pthread.h>
-
- #define N 100000
-
- int a[N] = {0};
- volatile int r = 0; // index to a
- volatile int w = 0; // index to a
-
- #define NotFull (w <= N - 1)
-
- #define NotEmpty (r < w)
- // w 是由生产者修改, 消费者要访问的
- void * Pthread(void *arg) // 生产者
- {
- printf("producer %u\n", pthread_self());
- while ( NotFull )
- {
- usleep(1);
- a[w] = w; // 模仿Stevens的进程间通信书中例子
- ++w;
- }
- return 0;
- }
-
- void * Cthread(void *arg) // 消费者
- {
- printf("consumer %u\n", pthread_self());
- while ( NotEmpty || NotFull )
- {
- usleep(1);
- if ( !NotEmpty)//消费的太快了
- continue;
-
- if ( r != a[r] )
-
- printf("ERROR : a[%d] = %d\n", r, a[r]);
- ++ r;
- }
- }
- int main()
- {
- pthread_t prod, con;
-
- pthread_create(&prod, NULL, Pthread, NULL);
- pthread_create(&con, NULL, Cthread, NULL);
-
- pthread_join(prod, NULL) ;
- pthread_join(con, NULL) ;
-
- return 0;
- }
作者: okocha-jay 发布时间: 2010-08-03
volatile 变量阿,如果你对访问变量的正确性不是很高要求的话,这样做应该没问题。
作者: davelv 发布时间: 2010-08-03
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28