-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
57 lines (45 loc) · 937 Bytes
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"log"
"sync"
)
type Server struct {
tasks map[TaskType]*TaskQueue
mu sync.RWMutex
}
func NewServer() *Server {
return &Server{tasks: make(map[TaskType]*TaskQueue)}
}
func (s *Server) RegisterTask(t TaskType) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.tasks[t]; ok {
log.Println("register task failed. task exists")
return false
}
s.tasks[t] = NewTaskQueue(t)
return true
}
func (s *Server) RegisterWorkerPool(t TaskType, pool *WorkerPool) bool {
s.mu.Lock()
defer s.mu.Unlock()
tq, ok := s.tasks[t]
if !ok {
log.Printf("register worker pool failed. task queue not exists.")
return false
}
pool.TaskQueue = tq
return true
}
func (s *Server) RunJob(t TaskType, args TaskArgs) TaskResult {
s.mu.RLock()
tq := s.tasks[t]
s.mu.RUnlock()
elem := &TaskElement{
Args: args,
Result: make(chan TaskResult),
}
tq.queue <- elem
res := <-elem.Result
return res
}