Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Created October 4, 2014 05:52
Show Gist options
  • Save tenntenn/2198a12596bb67cb16f5 to your computer and use it in GitHub Desktop.
Save tenntenn/2198a12596bb67cb16f5 to your computer and use it in GitHub Desktop.
Javaで書かれたWorkerThreadパターンのコードをGoで書きなおしてみた
package main
import (
"math/rand"
"time"
)
type Client struct {
name string
wp *WorkerPool
random *rand.Rand
}
func NewClient(name string, wp *WorkerPool) *Client {
return &Client{
name: name,
wp: wp,
random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (c *Client) String() string {
return c.name
}
func (c *Client) Run() {
for i := 0; true; i++ {
c.wp.RequestCh <- NewRequest(c.name, i)
time.Sleep(time.Duration(c.random.Intn(1000)) * time.Millisecond)
}
}
package main
import "time"
func main() {
wp := NewWorkerPool(5)
wp.Start()
go NewClient("Alice", wp).Run()
go NewClient("Bobby", wp).Run()
go NewClient("Chris", wp).Run()
time.Sleep(time.Minute)
}
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
type Request struct {
name string
number int
random *rand.Rand
}
func NewRequest(name string, number int) *Request {
return &Request{
name: name,
number: number,
random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (r *Request) Execute(w *Worker) {
log.Println(w.Name(), "executes", r)
time.Sleep(time.Duration(r.random.Intn(1000)) * time.Millisecond)
}
func (r *Request) String() string {
return fmt.Sprintf("[ Request from %s No. %d ]", r.name, r.number)
}
// WorkerThread.java
package main
type Worker struct {
name string
ch <-chan *Request
}
func NewWorker(name string, ch <-chan *Request) *Worker {
return &Worker{
name: name,
ch: ch,
}
}
func (w *Worker) Run() {
for r := range w.ch {
r.Execute(w)
}
}
func (w *Worker) String() string {
return w.name
}
func (w *Worker) Name() string {
return w.name
}
// Channel.java
package main
import "fmt"
const (
MAX_REQUEST int = 100
)
type WorkerPool struct {
RequestCh chan *Request
workers []*Worker
}
func NewWorkerPool(numWorkers int) *WorkerPool {
ch := make(chan *Request, MAX_REQUEST)
workers := make([]*Worker, numWorkers)
for i, _ := range workers {
name := fmt.Sprintf("Worker-%d", i)
workers[i] = NewWorker(name, ch)
}
return &WorkerPool{
RequestCh: ch,
workers: workers,
}
}
func (wp *WorkerPool) Start() {
for _, worker := range wp.workers {
go worker.Run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment