Created
January 7, 2015 08:30
-
-
Save ochinchina/d0574b02f07aa0771e35 to your computer and use it in GitHub Desktop.
go routine practice
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
// Goroutine practice | |
package main | |
import ( | |
"fmt" | |
"strconv" | |
"sync" | |
"time" | |
) | |
func test() { | |
fmt.Println("this is a go routine") | |
} | |
func test_goroutine_1() { | |
var i int = 0 | |
go func(x int) { | |
fmt.Printf("this is integer %d", x) | |
}(10) | |
for i = 0; i < 10; i++ { | |
test() | |
} | |
time.Sleep(5 * time.Second) | |
} | |
func test_goroutine_2() { | |
var wg sync.WaitGroup | |
var i int = 0 | |
for i = 0; i < 10; i++ { | |
wg.Add(1) | |
go func(msg string) { | |
defer wg.Done() | |
fmt.Printf("get message: %v", msg) | |
fmt.Println() | |
}("this is a simple message " + strconv.Itoa(i)) | |
} | |
wg.Wait() | |
} | |
func test_goroutine_3() { | |
mc := make(chan string) | |
go func(msgs ...string) { | |
for _, msg := range msgs { | |
mc <- msg | |
} | |
}("hello1", "hello2", "hello3") | |
go func() { | |
var i int = 0 | |
for i = 0; i < 3; i++ { | |
s := <-mc | |
fmt.Println(s) | |
} | |
}() | |
time.Sleep(5 * time.Second) | |
} | |
type Processor func(msg interface{}) | |
type ThreadPool struct { | |
n int | |
_stop bool | |
ch chan interface{} | |
} | |
func NewThreadPool(n int, processor Processor) *ThreadPool { | |
ch := make(chan interface{}) | |
tp := &ThreadPool{n, false, ch} | |
var i int = 0 | |
for i = 0; i < n; i++ { | |
go func() { | |
for !tp._stop { | |
msg := <-ch | |
processor(msg) | |
} | |
}() | |
} | |
return tp | |
} | |
func (tp *ThreadPool) submit(msg interface{}) *ThreadPool { | |
tp.ch <- msg | |
return tp | |
} | |
func (tp *ThreadPool) stop() { | |
tp._stop = true | |
tp.ch <- "quit" | |
} | |
func main() { | |
pool := NewThreadPool(10, func(msg interface{}) { | |
fmt.Println(msg) | |
}) | |
pool.submit("message1").submit("message2").submit("message3") | |
time.Sleep(2 * time.Second) | |
pool.stop() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment