semaphore
Let’s take a look at an over-simplified version of Golang runtime’s semaphore lock() implementation. If you’re interested, see the original version here.
Before you start, let’s make some assumptions to ease your understanding:
- a mutex l is an unsigned integer;
- it’s unlocked by default, having value 0;
- it’s locked by setting its value to 1;
1 | func lock(l *mutex) { |
What happens in the lock function can be summarized in the following points:
- if it is unlocked, grab it by setting it to 1;
- otherwise, we do some active spinnings to wait;
- before we start the spinning, if it is unlocked, grab it by setting it to 1;
- spin if we haven’t spent too much time actively waiting;
- otherwise, go to sleep;
- once wake up, start over from step 1;
Compare and Set.
Now, let me try to write some ugly pseudo code to summarize.
1 | run() { |
Leveled API
Feels familiar? This is actually a very typical controller in high level. And it’s called level-based API in Kubernetes. By “level-based”, we mean:
- we make no other assumptions about the world except our last observations;
- we make decisions completely based on our assumptions;
- we try to commit our decisions if our assumptions still hold, otherwise, we update our assumptions;
Why?
Some points I can think of:
- optimal concurrency control, thereby -> we get “optimal”;
- remain as stateless as possible;
- scalable;
- better manageability;
Distinct thought pattern? Or repeating history
CAS?
This is all I know, let’s move the world forward; otherwise, allow me to refresh my knowledge and try again.
Agile?
Some items copied from Wikipedia: Agile Overview
- Iterative, incremental;
- Efficient and face-to-face communication
- Very short feedback loop and adaptation cycle;
Similar?
Conclusion
In multithread programming, CAS or Optimal Concurrency Control is used to:
- capture my moment;
- make my contribution based on my understanding;
- try really hard to catch up with the real world;
Here, data is modified all the time by our peers, and we need to stay up to date with it to make changes.
In a team, Standup or Sprint Planning is used to achieve almost the same thing:
- (to market or customers or PM) what do you think?
- here is what I propose to solve your problem, does it still make sense?
- what’s on your mind now? let me know!
Yeah, if human were more advanced machines, why not manage them using the same way :) Of course, don’t forget to add Happiness on top.