A simple example to test synchronizing multiple goroutines.
This application has 4 goroutines:
- a ticker goroutine, sending data every 2 seconds to a monitor goroutine
- a monitoring goroutine that waits on a data channel, displaying its content when there is new data
- a user-input goroutine, waiting on
stdin
for user input, which is then sent to the control goroutine - a control goroutine that waits on a command channel, taking actions according to the received command ("d": display data, "t" display elapsed time", "w": quit)
$> go run main.go
2016/03/03 17:53:15 mon: 2016-03-03 16:53:15.124840889 +0000 UTC
d
2016/03/03 17:53:16 cmd: "d"
2016/03/03 17:53:16 today is 2016-03-03 17:53:16.865216802 +0100 CET
2016/03/03 17:53:17 mon: 2016-03-03 16:53:17.124858925 +0000 UTC
d
2016/03/03 17:53:17 cmd: "d"
2016/03/03 17:53:17 today is 2016-03-03 17:53:17.409236028 +0100 CET
t
2016/03/03 17:53:18 cmd: "t"
2016/03/03 17:53:18 elapsed: 5.05254336s
2016/03/03 17:53:19 mon: 2016-03-03 16:53:19.124846239 +0000 UTC
d
2016/03/03 17:53:19 cmd: "d"
2016/03/03 17:53:19 today is 2016-03-03 17:53:19.713227 +0100 CET
2016/03/03 17:53:21 mon: 2016-03-03 16:53:21.124851038 +0000 UTC
t
2016/03/03 17:53:21 cmd: "t"
2016/03/03 17:53:21 elapsed: 8.284506582s
2016/03/03 17:53:23 mon: 2016-03-03 16:53:23.124853101 +0000 UTC
2016/03/03 17:53:25 mon: 2016-03-03 16:53:25.124852105 +0000 UTC
2016/03/03 17:53:27 mon: 2016-03-03 16:53:27.124854667 +0000 UTC
q
2016/03/03 17:53:28 cmd: "q"
2016/03/03 17:53:28 goroutine-control exiting...
2016/03/03 17:53:28 goroutine-monitor exiting...
2016/03/03 17:53:28 goroutine-usr-input exiting...
2016/03/03 17:53:28 scanner-goroutine exiting...
2016/03/03 17:53:28 ticker exiting...
bye.