[英]Static threaded flag and -O3
我尝试编写一个单一的生产者消费者实现。 我在使用优化进行编译时遇到了问题。 在 gcc 中使用优化 (-O3) 运行时,线程卡住了。
添加 volatile 或从全局标志中删除 static 时,线程按预期工作。 为什么是这样?
#include <stdio.h>
#include <pthread.h>
static volatile int flag = 0; /* this is the line */
static int resource = 0;
void *Writer(void *somthing);
void *Reader(void *somthing);
int main()
{
pthread_t id1 = 0;
pthread_t id2 = 0;
pthread_create(&id1, NULL, Writer, NULL);
pthread_create(&id2, NULL, Reader, NULL);
return 0;
}
void *Writer(void *somthing)
{
while(1)
{
while (1 == flag);
++resource;
flag = 1;
}
return NULL;
}
void *Reader(void *somthing)
{
while(1)
{
while(0 == flag);
fprintf(stderr,"%d\n",resource);
flag = 0;
}
return NULL;
}```
如果你正在写一个编译器,你发现
while(flag == 1)
;
你会怎么做? 我会优化它,因为flag
不可能在循环内改变。
但是,在某些情况下,其他事情可能会在您不知情的情况下更改flag
。 这就是volatile
的作用:它告诉编译器期待未预料到的。
volatile
向编译器显示 object “容易产生副作用”,这意味着它可以被不在正常程序执行路径上的东西改变。
每次使用时, voaltile
object 将从其 memory 位置读取。 程序每次修改都会更新其memory存储
区别很容易在这里发现。 https://godbolt.org/z/s1beqq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.