-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathprim_concurrency.go
423 lines (334 loc) · 11.8 KB
/
prim_concurrency.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2014 SteelSeries ApS. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file contains the concurrency primitive functions.
package golisp
import (
"fmt"
"runtime"
"strings"
"sync/atomic"
"time"
"unsafe"
)
type empty struct{}
type Process struct {
Env *SymbolTableFrame
Code *Data
Wake chan empty
Abort chan empty
Restart chan empty
ReturnValue chan *Data
Joined int32
ScheduleTimer *time.Timer
}
func RegisterConcurrencyPrimitives() {
MakePrimitiveFunction("fork", ">=1", ForkImpl)
MakePrimitiveFunction("proc-sleep", "2", ProcSleepImpl)
MakePrimitiveFunction("wake", "1", WakeImpl)
MakePrimitiveFunction("schedule", ">=2", ScheduleImpl)
MakePrimitiveFunction("reset-timeout", "1", ResetTimeoutImpl)
MakePrimitiveFunction("abandon", "1", AbandonImpl)
MakePrimitiveFunction("join", "1", JoinImpl)
MakePrimitiveFunction("atomic", "0|1", AtomicImpl)
MakePrimitiveFunction("atomic-load", "1", AtomicLoadImpl)
MakePrimitiveFunction("atomic-store!", "2", AtomicStoreImpl)
MakePrimitiveFunction("atomic-add!", "2", AtomicAddImpl)
MakePrimitiveFunction("atomic-swap!", "2", AtomicSwapImpl)
MakePrimitiveFunction("atomic-compare-and-swap!", "3", AtomicCompareAndSwapImpl)
}
func ForkImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
f := Car(args)
if !FunctionP(f) {
err = ProcessError(fmt.Sprintf("fork expected a function, but received %v.", f), env)
return
}
argsCount := Length(Cdr(args)) + 1
function := FunctionValue(f)
if function.VarArgs {
if argsCount < function.RequiredArgCount {
return nil, ProcessError(fmt.Sprintf("fork expected a function with arity of at most %d, but it was %d.", argsCount, function.RequiredArgCount), env)
}
} else {
if argsCount != function.RequiredArgCount {
return nil, ProcessError(fmt.Sprintf("fork expected a function with arity of %d, but it was %d.", argsCount, function.RequiredArgCount), env)
}
}
proc := &Process{
Env: env,
Code: f,
Wake: make(chan empty, 1),
Abort: make(chan empty, 1),
Restart: make(chan empty, 1),
ReturnValue: make(chan *Data, 1)}
procObj := ObjectWithTypeAndValue("Process", unsafe.Pointer(proc))
function.ParentProcess = proc
go func() {
var returnValue *Data
defer func() {
proc.ReturnValue <- returnValue
}()
callWithPanicProtection(func() {
var forkedErr error
returnValue, forkedErr = function.ApplyWithoutEval(Cons(procObj, Cdr(args)), env)
if forkedErr != nil {
fmt.Println(forkedErr)
}
}, "fork")
}()
return procObj, nil
}
func ProcSleepImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
procObj := Car(args)
if !ObjectP(procObj) || ObjectType(procObj) != "Process" {
err = ProcessError(fmt.Sprintf("proc-sleep expects a Process object expected but received %s.", ObjectType(procObj)), env)
return
}
proc := (*Process)(ObjectValue(procObj))
millis := Cadr(args)
if !IntegerP(millis) {
err = ProcessError(fmt.Sprintf("proc-sleep expected an integer as a delay, but received %v.", millis), env)
return
}
woken := false
select {
case <-proc.Wake:
woken = true
case <-time.After(time.Duration(IntegerValue(millis)) * time.Millisecond):
}
return BooleanWithValue(woken), nil
}
func WakeImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
procObj := Car(args)
if !ObjectP(procObj) || ObjectType(procObj) != "Process" {
err = ProcessError(fmt.Sprintf("wake expects a Process object expected but received %s.", ObjectType(procObj)), env)
return
}
proc := (*Process)(ObjectValue(procObj))
select {
case proc.Wake <- empty{}:
default:
}
return StringWithValue("OK"), nil
}
func ScheduleImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
millis := Car(args)
if !IntegerP(millis) {
err = ProcessError(fmt.Sprintf("schedule expected an integer as a delay, but received %v.", millis), env)
return
}
f := Cadr(args)
if !FunctionP(f) {
err = ProcessError(fmt.Sprintf("schedule expected a function, but received %v.", f), env)
return
}
argsCount := Length(Cddr(args)) + 1
function := FunctionValue(f)
if function.VarArgs {
if argsCount < function.RequiredArgCount {
return nil, ProcessError(fmt.Sprintf("schedule expected a function with arity of at most %d, but it was %d.", argsCount, function.RequiredArgCount), env)
}
} else {
if argsCount != function.RequiredArgCount {
return nil, ProcessError(fmt.Sprintf("schedule expected a function with arity of %d, but it was %d.", argsCount, function.RequiredArgCount), env)
}
}
proc := &Process{
Env: env,
Code: f,
Wake: make(chan empty, 1),
Abort: make(chan empty, 1),
Restart: make(chan empty, 1),
ReturnValue: make(chan *Data, 1),
ScheduleTimer: time.NewTimer(time.Duration(IntegerValue(millis)) * time.Millisecond)}
procObj := ObjectWithTypeAndValue("Process", unsafe.Pointer(proc))
function.ParentProcess = proc
go func() {
var returnValue *Data
defer func() {
proc.ReturnValue <- returnValue
}()
callWithPanicProtection(func() {
Loop:
for {
select {
case <-proc.Abort:
break Loop
case <-proc.Restart:
proc.ScheduleTimer.Reset(time.Duration(IntegerValue(millis)) * time.Millisecond)
case <-proc.ScheduleTimer.C:
var forkedErr error
returnValue, forkedErr = function.ApplyWithoutEval(Cons(procObj, Cddr(args)), env)
if forkedErr != nil {
fmt.Println(forkedErr)
}
break Loop
}
}
}, "schedule")
}()
return procObj, nil
}
func AbandonImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
procObj := Car(args)
if !ObjectP(procObj) || ObjectType(procObj) != "Process" {
err = ProcessError(fmt.Sprintf("adandon expects a Process object expected but received %s.", ObjectType(procObj)), env)
return
}
proc := (*Process)(ObjectValue(procObj))
if proc.ScheduleTimer == nil {
return nil, ProcessError("tried to adandon a Process that isn't scheduled", env)
}
select {
case proc.Abort <- empty{}:
default:
}
return StringWithValue("OK"), nil
}
func ResetTimeoutImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
procObj := Car(args)
if !ObjectP(procObj) || ObjectType(procObj) != "Process" {
err = ProcessError(fmt.Sprintf("restart expects a Process object expected but received %s.", ObjectType(procObj)), env)
return
}
proc := (*Process)(ObjectValue(procObj))
if proc.ScheduleTimer == nil {
return nil, ProcessError("tried to reset a Process that isn't scheduled", env)
}
var str string
select {
case proc.Restart <- empty{}:
str = "OK"
default:
str = "task was already completed or abandoned"
}
return StringWithValue(str), nil
}
func JoinImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
procObj := Car(args)
if !ObjectP(procObj) || ObjectType(procObj) != "Process" {
err = ProcessError(fmt.Sprintf("join expects a Process object but received %s.", ObjectType(procObj)), env)
return
}
proc := (*Process)(ObjectValue(procObj))
// Check for early exit if joining on the current proc
parentProcData := env.ValueOf(SymbolWithName("parentProcess"))
if NotNilP(parentProcData) && ObjectP(parentProcData) && ObjectType(parentProcData) == "Process" {
parentProc := (*Process)(ObjectValue(parentProcData))
if proc == parentProc {
// Oh no, we're in our own process! Bail out!
// But we want it to complete, so we're not treating it as an error
return nil, nil
}
}
if atomic.CompareAndSwapInt32(&proc.Joined, 0, 1) {
return <-proc.ReturnValue, nil
}
return nil, ProcessError("tried to join on a task twice", env)
}
func AtomicImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicVal := int64(0)
if Length(args) == 1 {
initObj := Car(args)
if !IntegerP(initObj) {
err = ProcessError(fmt.Sprintf("atomic expects an Integer as its argument but received %s.", TypeName(TypeOf(initObj))), env)
return
}
atomicVal = IntegerValue(initObj)
}
return ObjectWithTypeAndValue("Atomic", unsafe.Pointer(&atomicVal)), nil
}
func AtomicLoadImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicObj := Car(args)
if !ObjectP(atomicObj) || ObjectType(atomicObj) != "Atomic" {
err = ProcessError(fmt.Sprintf("atomic-load expects an Atomic object but received %s.", ObjectType(atomicObj)), env)
return
}
pointer := (*int64)(ObjectValue(atomicObj))
value := atomic.LoadInt64(pointer)
return IntegerWithValue(value), nil
}
func AtomicStoreImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicObj := Car(args)
if !ObjectP(atomicObj) || ObjectType(atomicObj) != "Atomic" {
err = ProcessError(fmt.Sprintf("atomic-store! expects an Atomic object but received %s.", ObjectType(atomicObj)), env)
return
}
pointer := (*int64)(ObjectValue(atomicObj))
newObj := Cadr(args)
if !IntegerP(newObj) {
err = ProcessError(fmt.Sprintf("atomic-store! expects an Integer as its second argument but received %s.", TypeName(TypeOf(newObj))), env)
return
}
new := IntegerValue(newObj)
atomic.StoreInt64(pointer, new)
return
}
func AtomicAddImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicObj := Car(args)
if !ObjectP(atomicObj) || ObjectType(atomicObj) != "Atomic" {
err = ProcessError(fmt.Sprintf("atomic-add! expects an Atomic object but received %s.", ObjectType(atomicObj)), env)
return
}
pointer := (*int64)(ObjectValue(atomicObj))
deltaObj := Cadr(args)
if !IntegerP(deltaObj) {
err = ProcessError(fmt.Sprintf("atomic-add! expects an Integer as its second argument but received %s.", TypeName(TypeOf(deltaObj))), env)
return
}
delta := IntegerValue(deltaObj)
new := atomic.AddInt64(pointer, delta)
return IntegerWithValue(new), nil
}
func AtomicSwapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicObj := Car(args)
if !ObjectP(atomicObj) || ObjectType(atomicObj) != "Atomic" {
err = ProcessError(fmt.Sprintf("atomic-swap! expects an Atomic object but received %s.", ObjectType(atomicObj)), env)
return
}
pointer := (*int64)(ObjectValue(atomicObj))
newObj := Cadr(args)
if !IntegerP(newObj) {
err = ProcessError(fmt.Sprintf("atomic-swap! expects an Integer as its second argument but received %s.", TypeName(TypeOf(newObj))), env)
return
}
new := IntegerValue(newObj)
old := atomic.SwapInt64(pointer, new)
return IntegerWithValue(old), nil
}
func AtomicCompareAndSwapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
atomicObj := Car(args)
if !ObjectP(atomicObj) || ObjectType(atomicObj) != "Atomic" {
err = ProcessError(fmt.Sprintf("atomic-compare-and-swap! expects an Atomic object but received %s.", ObjectType(atomicObj)), env)
return
}
pointer := (*int64)(ObjectValue(atomicObj))
oldObj := Cadr(args)
if !IntegerP(oldObj) {
err = ProcessError(fmt.Sprintf("atomic-compare-and-swap! expects an Integer as its second argument but received %s.", TypeName(TypeOf(oldObj))), env)
return
}
newObj := Caddr(args)
if !IntegerP(newObj) {
err = ProcessError(fmt.Sprintf("atomic-compare-and-swap! expects an Integer as its third argument but received %s.", TypeName(TypeOf(newObj))), env)
return
}
old := IntegerValue(oldObj)
new := IntegerValue(newObj)
swapped := atomic.CompareAndSwapInt64(pointer, old, new)
return BooleanWithValue(swapped), nil
}
func callWithPanicProtection(f func(), prefix string) {
defer func() {
if recovered := recover(); recovered != nil {
stackBuf := make([]byte, 10000)
stackBuf = stackBuf[:runtime.Stack(stackBuf, false)]
stack := strings.Split(string(stackBuf), "\n")
for i := 0; i < 7; i++ {
fmt.Println(stack[i])
}
}
}()
f()
}