-
Notifications
You must be signed in to change notification settings - Fork 7
/
pool.go
133 lines (105 loc) · 2.24 KB
/
pool.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package nanopow
import (
"encoding/binary"
"runtime"
"sync"
)
type Context struct {
results chan uint64
stops chan bool
closed bool
mutex *sync.Mutex
}
func NewContext() *Context {
return &Context{
results: make(chan uint64, 64),
stops: make(chan bool),
closed: false,
mutex: new(sync.Mutex),
}
}
func (c *Context) workerStop() <-chan bool {
return c.stops
}
func (c *Context) workerResult(i uint64) {
c.mutex.Lock()
if !c.closed {
c.results <- i
}
c.mutex.Unlock()
}
func (c *Context) Cancel() {
c.mutex.Lock()
close(c.stops)
close(c.results)
clear(c.results)
c.closed = true
c.mutex.Unlock()
}
func (c *Context) Result() (result Work) {
r := <-c.results
c.Cancel()
binary.BigEndian.PutUint64(result[:], r)
return result
}
func clear(r chan uint64) {
for len(r) > 0 {
<-r
}
}
type WorkerGenerator interface {
GenerateWork(ctx *Context, root []byte, difficulty uint64) (err error)
}
type Pool struct {
Workers []WorkerGenerator
}
func NewPool(w ...WorkerGenerator) (p *Pool) {
return &Pool{Workers: w}
}
func (p *Pool) GenerateWork(root []byte, difficulty uint64) (w Work, err error) {
ctx := NewContext()
for _, wk := range p.Workers {
if wk == nil {
continue
}
go wk.GenerateWork(ctx, root, difficulty)
}
return ctx.Result(), nil
}
func GenerateWork(root []byte, difficulty uint64) (w Work, err error) {
defaultWorker := getDefaultWorkerPool()
if defaultWorker == nil || defaultWorker.Workers == nil {
return w, ErrNoDefaultPoolAvailable
}
return defaultWorker.GenerateWork(root, difficulty)
}
var DefaultWorkerPool *Pool // We don't use DefaultWorkerPool = newDefaultPool() because it slow down the init
func getDefaultWorkerPool() (p *Pool) {
if DefaultWorkerPool == nil {
DefaultWorkerPool = newDefaultPool()
}
return DefaultWorkerPool
}
func newDefaultPool() (p *Pool) {
p = new(Pool)
clDevice, gpuErr := GetDevice()
if gpuErr != nil {
gpu, gpuErr := NewWorkerGPU(clDevice)
if gpuErr == nil {
p.Workers = append(p.Workers, gpu)
}
}
threads := runtime.NumCPU()
if gpuErr == nil {
if threads >= 8 {
threads /= 2
} else {
return p
}
}
cpu, cpuErr := NewWorkerCPUThread(uint64(threads))
if cpuErr == nil {
p.Workers = append(p.Workers, cpu)
}
return p
}