Discussions of the Parallel Programming book
 help / color / mirror / Atom feed
* synchronize with a non-atomic flag
@ 2017-10-06  5:52 Yubin Ruan
  2017-10-06 12:03 ` Akira Yokosawa
  2017-10-08  9:12 ` Yubin Ruan
  0 siblings, 2 replies; 13+ messages in thread
From: Yubin Ruan @ 2017-10-06  5:52 UTC (permalink / raw)
  To: perfbook

Hi,
I saw lots of discussions on the web about possible race when doing
synchronization between multiple threads/processes with lock or atomic
operations[1][2]. From my point of view most them are over-worrying.
But I want to point out some particular issue here to see whether
anyone have anything to say.

Imagine two processes communicate using only a uint32_t variable in
shared memory, like this:

    // uint32_t variable in shared memory
    uint32_t flag = 0;

    //process 1
    while(1) {
        if(READ_ONCE(flag) == 0) {
            do_something();
            WRITE_ONCE(flag, 1); // let another process to run
        } else {
            continue;
        }
    }

    //process 2
    while(1) {
        if(READ_ONCE(flag) == 1) {
            printf("process 2 running...\n");
            WRITE_ONCE(flag, 0); // let another process to run
        } else {
            continue;
        }
    }

On X86 or X64, I expect this code to run correctly, that is, I will
got the two `printf' to printf one after one. That is because:

    1) on X86/X64, load/store on 32-bits variable are atomic
    2) I use READ_ONCE/WRITE_ONCE to prevent possibly harmful compiler
optimization on `flag'.
    3) I use only one variable to communicate between two processes,
so there is no need for any kind of barrier.

Does anyone have any objection at that?

I know using a lock or atomic operation will save me a lot of
argument, but I think those things are unnecessary at this
circumstance, and it matter where performance matter, so I am picky
here...

Yubin

[1]: https://software.intel.com/en-us/blogs/2013/01/06/benign-data-races-what-could-possibly-go-wrong
[2]: https://www.usenix.org/conference/osdi10/ad-hoc-synchronization-considered-harmful

^ permalink raw reply	[flat|nested] 13+ messages in thread

end of thread, other threads:[~2017-10-09  8:40 UTC | newest]

Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2017-10-06  5:52 synchronize with a non-atomic flag Yubin Ruan
2017-10-06 12:03 ` Akira Yokosawa
2017-10-06 12:35   ` Yubin Ruan
2017-10-06 19:12     ` Paul E. McKenney
2017-10-07  7:04       ` Yubin Ruan
2017-10-07 11:40         ` Akira Yokosawa
2017-10-07 13:43           ` Yubin Ruan
2017-10-07 14:36             ` Akira Yokosawa
2017-10-07 20:20               ` Paul E. McKenney
2017-10-08  9:12 ` Yubin Ruan
2017-10-08 16:07   ` Paul E. McKenney
2017-10-09  8:40     ` Yubin Ruan
2017-10-09  2:14       ` Paul E. McKenney

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox