Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since you are making a distributed lock service, I assume your lock server listens on a port, and when you accept() a connection you loop, waiting for commands in a goroutine per connection. And that goroutine exits when the socket is dropped (ie: remote node crash)</p> <p>So, assuming that is true, you can do a couple things.</p> <p>1) create a channel with a depth matching how many concurrent locks 2) when you lock, send a message to the channel (it will block if full) 3) when you unlock, just read a message from the channel 4) you can "defer release()" (where release consumes a message if you have already locked)</p> <p>Here's a rough working example, all but the socket stuff. Hopefully it makes sense. <a href="http://play.golang.org/p/DLOX7m8m6q" rel="nofollow">http://play.golang.org/p/DLOX7m8m6q</a></p> <pre><code>package main import "fmt" import "time" type Locker struct { ch chan int locked bool } func (l *Locker) lock(){ l.ch &lt;- 1 l.locked=true } func (l *Locker) unlock() { if l.locked { // called directly or via defer, make sure we don't unlock if we don't have the lock l.locked = false // avoid unlocking twice if socket crashes after unlock &lt;- l.ch } } func dostuff(name string, locker Locker) { locker.lock() defer locker.unlock() fmt.Println(name,"Doing stuff") time.Sleep(1 * time.Second) } func main() { ch := make(chan int, 2) go dostuff("1",Locker{ch,false}) go dostuff("2",Locker{ch,false}) go dostuff("3",Locker{ch,false}) go dostuff("4",Locker{ch,false}) time.Sleep(4 * time.Second) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload