简体   繁体   English

Static 线程标志和 -O3

[英]Static threaded flag and -O3

I tried writing a single producer consumer implementation.我尝试编写一个单一的生产者消费者实现。 I encountered a problem when compiling with optimizations.我在使用优化进行编译时遇到了问题。 When running with optimizations (-O3) in gcc, the threads got stuck.在 gcc 中使用优化 (-O3) 运行时,线程卡住了。

When adding volatile, or removing the static from the global flag, the threads worked as expected.添加 volatile 或从全局标志中删除 static 时,线程按预期工作。 Why is this?为什么是这样?

#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;
}```

If you were writing a compiler, and you found如果你正在写一个编译器,你发现

while(flag == 1)
   ;

what would you do?你会怎么做? I would optimise it out, because flag can't possibly change inside the loop.我会优化它,因为flag不可能在循环内改变。

But, in some cases, something else could possibly change flag without you knowing.但是,在某些情况下,其他事情可能会在您不知情的情况下更改flag That's what volatile is for: it tells the compiler to expect the unxecpected.这就是volatile的作用:它告诉编译器期待未预料到的。

volatile shows the compiler that object is "side effect prone" which means that it can be changed by something which is not on the normal program execution path. volatile向编译器显示 object “容易产生副作用”,这意味着它可以被不在正常程序执行路径上的东西改变。

voaltile object will be read from its memory location every time it is used.每次使用时, voaltile object 将从其 memory 位置读取。 Program will update its memory storage every time it is modified程序每次修改都会更新其memory存储

The difference is very easy to spot here.区别很容易在这里发现。 https://godbolt.org/z/s1beqq https://godbolt.org/z/s1beqq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM