Wrong implementation of Peterson's algorithm?

前端 未结 1 619
生来不讨喜
生来不讨喜 2020-12-21 10:57

I was trying to learn something about parallel programming, so I tried to implement Peterson\'s algorithm for an easy example where one shared counter is incremented by 2 th

相关标签:
1条回答
  • 2020-12-21 11:51

    You have several problems here:

    • the access to your variables will we subject to optimization, so you'd have to declare them volatile, at least.
    • Algorithms like this that access data between threads without any of the lock data structures that are provided by POSIX can only work if your primitive operations are guaranteed to be atomic, which they usually aren't on modern processors. In particular the ++ operator is not atomic.

    There would be several ways around this, in particular the new C standard C11 offers atomic primitives. But if this is really meant for you as a start to learn parallel programming, I'd strongly suggest that you first look into mutexes, condition variables etc, to learn how POSIX is intended to work.

    0 讨论(0)
提交回复
热议问题