Skip to content

Instantly share code, notes, and snippets.

@bwangelme
Created April 14, 2019 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwangelme/1d204647f4658007043f348a61f37936 to your computer and use it in GitHub Desktop.
Save bwangelme/1d204647f4658007043f348a61f37936 to your computer and use it in GitHub Desktop.

在公平锁解法的代码中,程序可以保证上锁和解锁顺序是一致的,但无法保证三个 Goroutine 的启动顺序。

假设三个线程的启动顺序是 C,B,A

那么它们的上锁顺序就是 C,B,A,C,B,A,C,B,A,C,B,A...,为了方便描述,我给它们标上上了序号

上锁线程 C B A C B A C B A C B A
上锁编号 0 1 2 3 4 5 6 7 8 9 10 11

在符合 i < 3 的条件下,上锁编号为0,1,3,5的操作都会直接continue,不会输出任何值。当i>=3之后,所有操作都会直接将值输出,所以可以看到后面就会按着B,A,C的顺序来输出了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment