Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

q001.md #3

Closed
Jancd opened this issue Sep 12, 2018 · 1 comment
Closed

q001.md #3

Jancd opened this issue Sep 12, 2018 · 1 comment

Comments

@Jancd
Copy link

Jancd commented Sep 12, 2018

看到前面已经有一个关于这个问题的讨论,我还是选择了开了一个新的issue谈谈我的想法。


除了使用加锁的方法,还可以使用channel来实现goroutine调度,这是一个典型的 pingpong的问题,加上一个channel接受完成通知就好。


package main

import (
	"fmt"
)

func main() {
	ping := make(chan struct{}, 1)
	pong := make(chan struct{}, 1)
	done := make(chan struct{})

	ping <- struct{}{}
	go func() {
		for i := 0; i < 10; i++ {
			<-ping
			fmt.Print(i)
			pong <- struct{}{}
		}
	}()

	go func() {
		for i := 0; i < 10; i++ {
			<-pong
			fmt.Printf("%c", 'A'+i)
			ping <- struct{}{}
		}
		done <- struct{}{}
	}()

	<-done
	close(ping)
	close(pong)
}
@Jancd
Copy link
Author

Jancd commented Sep 12, 2018

对了,上述代码忘了 close(done)

@Jancd Jancd closed this as completed Sep 16, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant