Last active
August 29, 2015 13:56
-
-
Save kiyor/9240165 to your computer and use it in GitHub Desktop.
golang basic multi client run queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. | |
* File Name : main.go | |
* Purpose : | |
* Creation Date : 02-26-2014 | |
* Last Modified : Wed 26 Feb 2014 01:30:21 AM UTC | |
* Created By : Kiyor | |
_._._._._._._._._._._._._._._._._._._._._.*/ | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"runtime" | |
"sync" | |
"time" | |
) | |
type client struct { | |
conn interface{} | |
loc *bool | |
} | |
func (c *client) lock() { | |
*c.loc = true | |
} | |
func (c *client) unlock() { | |
*c.loc = false | |
} | |
type worker struct { | |
sync.WaitGroup | |
counter *int | |
} | |
func (w *worker) add(n int) { | |
w.Add(n) | |
*w.counter += n | |
} | |
func (w *worker) done() { | |
*w.counter-- | |
w.Done() | |
} | |
func initClient() client { | |
var conn interface{} | |
return client{conn, new(bool)} | |
} | |
func (c *client) doSomething(id, index int, w worker) { | |
r := random(5) | |
for i := 0; i < random(5); i++ { | |
time.Sleep(1 * time.Second) | |
} | |
fmt.Printf("I'm doing process[%d] in client[%d] and finish it using %d seconds, running %d\n", index, id, r, *w.counter-1) | |
c.unlock() | |
} | |
func random(rg int) int { | |
return rand.Intn(rg) + 1 | |
} | |
func getClient(clients []client) int { | |
for { | |
for k, c := range clients { | |
if !*c.loc { | |
c.lock() | |
return k | |
} | |
} | |
time.Sleep(1 * time.Millisecond) | |
} | |
} | |
var ( | |
clients []client | |
size = 10 | |
process = 100 | |
) | |
func init() { | |
runtime.GOMAXPROCS(runtime.NumCPU()) | |
for i := 0; i < size; i++ { | |
clients = append(clients, initClient()) | |
} | |
} | |
func main() { | |
var w worker | |
w.counter = new(int) | |
for i := 0; i < process; i++ { | |
w.add(1) | |
id := getClient(clients) | |
go func(id, i int, w *worker) { | |
clients[id].doSomething(id, i, *w) | |
w.done() | |
}(id, i, &w) | |
} | |
w.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment