|
|
Subscribe / Log in / New account

Example, read once may or may not be the "right thing".

Example, read once may or may not be the "right thing".

Posted Apr 9, 2020 5:45 UTC (Thu) by gmatht (guest, #58961)
In reply to: Who's afraid of a big bad optimizing compiler? by excors
Parent article: Who's afraid of a big bad optimizing compiler?

We even have an example in the article of different code making incompatible assumptions. Here the code assumes the variable need_to_stop will be read many times.

1 while (!need_to_stop) /* BUGGY!!! */
2     do_something_quickly();

The following code is instead assuming that global_ptr won't change. This could be ensured by only reading global_ptr once.

2 if (global_ptr != NULL &&
3     global_ptr < high_address)
4         do_low(global_ptr);

In general it might be hard to determine which of these two contradictory assumptions the code is making.


to post comments

Example, read once may or may not be the "right thing".

Posted Apr 9, 2020 8:30 UTC (Thu) by geert (subscriber, #98403) [Link] (1 responses)

Isn't this the reason for the existence of the "volatile" keyword, and why need_to_stop should be annotated with it?

Example, read once may or may not be the "right thing".

Posted Apr 10, 2020 17:22 UTC (Fri) by zlynx (guest, #2285) [Link]

The "volatile" keyword is almost completely useless. It's good for reading memory mapped hardware and signal handlers. And not even signal handlers if you're using multiple threads.

In any thread situation you want an atomic access. Which might be implemented using volatile, but requires more than that such as memory barrier operations.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds