I see that others have already addressed the locking issued, but I noticed 
something else.  I don’t understand why you are using “select”.  With only one 
case, I think that it’s normally going to fail and exit the select block, then 
loop due to the “for”.  This will make it run constantly.

 

If you get rid of the “select” then the loop will block until something comes 
in from the channel.  

 

John

    John Souvestre - New Orleans LA

 

From: golang-nuts@googlegroups.com [mailto:golang-nuts@googlegroups.com] On 
Behalf Of liminglang...@gmail.com
Sent: 2016 October 11, Tue 21:26
To: golang-nuts
Subject: [go-nuts] infinite loop makes program stuck

 

Hi, there. I've read the FAQ and specifically the concurrency part. Tell me if 
the problem has been discussed anywhere.

 

I used an infinite loop to block a goroutine until a value is big enough:

 

for commitIndex < index {}

 

I know its bad but its just a very intuitive and fast to implement. And I 
incremented commitIndex in another goroutine monotonically:

 

for {

    select {
    case <-ch:
      mu.Lock()
      commitIndex++
      mu.Unlock()

    }

}

 

These are the only two places that access commitIndex. I didn't acquire the 
lock when reading commitIndex since I think its OK to read a stale value in my 
case. The program is a complex Raft replicated server so there're many other 
goroutines. The problem is the program became stuck after running for a while. 
commitIndex stopped updating and even the Raft servers stopped communicating 
with each other. I ended up adding a Sleep() in the for loop and everything 
worked. Is this normal? Or there's a problem with the goroutine scheduling?

 

 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to