From f99c2d2799ec0a7b3c1ad62088962f025254b1de Mon Sep 17 00:00:00 2001 From: alanchenchen <739709491@qq.com> Date: Wed, 22 Apr 2020 11:53:41 +0800 Subject: [PATCH] [F] limit only one goroutine to start spinner --- README.md | 2 +- spin.go | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6cf2708..b8b2a22 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ a terminal spinner for golang > Author:Alan Chen -> Date: 2020/4/20 +> Date: 2020/4/22 ## features 1. 使用goroutine来运行spinner。 diff --git a/spin.go b/spin.go index e54546c..66da131 100644 --- a/spin.go +++ b/spin.go @@ -2,10 +2,11 @@ package spin import ( "fmt" + "os" "time" ) -const threadsNum uint = 1 +const lockThreadsNum uint = 1 // spin character type character struct { @@ -15,10 +16,10 @@ type character struct { // spin content type Spin struct { - shouldWork bool - threadsNum uint - character character - ch chan bool + shouldWork bool + lockThreadsNum uint + character character + ch chan bool } func (s *Spin) run() { @@ -43,10 +44,14 @@ func (s *Spin) waitForRun() { // start spinning func (s *Spin) Start() { - if s.threadsNum <= 1 { + if s.lockThreadsNum == 1 { go s.waitForRun() go s.run() + } else { + fmt.Println("current spin locks only one goroutine, so don't call start method multiple times") + os.Exit(1) } + s.lockThreadsNum++ } // stop spinning @@ -83,7 +88,7 @@ func (s *Spin) Fail(text string) { func New(spinType character) *Spin { s := new(Spin) s.shouldWork = true - s.threadsNum = threadsNum + s.lockThreadsNum = lockThreadsNum s.character = spinType s.ch = make(chan bool) return s