-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.go
43 lines (36 loc) · 829 Bytes
/
thread.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
package Thread
import (
"log"
"sync"
"time"
)
type Pool struct {
MaxThread int
chParams chan interface{}
waitGroup sync.WaitGroup
function func(param interface{})
}
func (tp *Pool) Prepare(function func(item interface{})) {
tp.chParams = make(chan interface{}, tp.MaxThread)
tp.waitGroup = sync.WaitGroup{}
tp.function = function
for i := 0; i < tp.MaxThread; i++ {
workerId := i
go func() {
tp.waitGroup.Add(1)
defer tp.waitGroup.Done()
log.Printf("Worker [%d] started at %d\n", workerId, time.Now().Unix())
for param := range tp.chParams {
tp.function(param)
}
log.Printf("Worker [%d] finished at %d\n", workerId, time.Now().Unix())
}()
}
}
func (tp *Pool) RunWith(param interface{}) {
tp.chParams <- param
}
func (tp *Pool) Wait() {
close(tp.chParams)
tp.waitGroup.Wait()
}