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.
When adding volatile, or removing the static from the global flag, the threads worked as expected. 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.
But, in some cases, something else could possibly change flag
without you knowing. That's what volatile
is for: it tells the compiler to expect the unxecpected.
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.
voaltile
object will be read from its memory location every time it is used. Program will update its memory storage every time it is modified
The difference is very easy to spot here. https://godbolt.org/z/s1beqq
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.