forked from opal/opal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.rb
More file actions
163 lines (128 loc) · 2.57 KB
/
thread.rb
File metadata and controls
163 lines (128 loc) · 2.57 KB
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
# This shim implementation of Thread is meant to only appease code that tries
# to be safe in the presence of threads, but does not actually utilize them,
# e.g., uses thread- or fiber-local variables.
class ThreadError < StandardError
end
class Thread
def self.current
unless @current
@current = allocate
@current.core_initialize!
end
@current
end
def self.list
[current]
end
# Do not allow creation of new instances.
def initialize(*args)
raise NotImplementedError, 'Thread creation not available'
end
# fiber-local attribute access.
def [](key)
@fiber_locals[coerce_key_name(key)]
end
def []=(key, value)
@fiber_locals[coerce_key_name(key)] = value
end
def key?(key)
@fiber_locals.key?(coerce_key_name(key))
end
def keys
@fiber_locals.keys
end
# thread-local attribute access.
def thread_variable_get(key)
@thread_locals[coerce_key_name(key)]
end
def thread_variable_set(key, value)
@thread_locals[coerce_key_name(key)] = value
end
def thread_variable?(key)
@thread_locals.key?(coerce_key_name(key))
end
def thread_variables
@thread_locals.keys
end
private
def core_initialize!
@thread_locals = {}
@fiber_locals = {}
end
def coerce_key_name(key)
Opal.coerce_to!(key, String, :to_s)
end
class Queue
def initialize
clear
end
def clear
@storage = []
end
def empty?
@storage.empty?
end
def size
@storage.size
end
alias length size
def pop(non_block = false)
if empty?
raise ThreadError, 'Queue empty' if non_block
raise ThreadError, 'Deadlock'
end
@storage.shift
end
alias shift pop
alias deq pop
def push(value)
@storage.push(value)
end
alias << push
alias enq push
def each(&block)
@storage.each(&block)
end
end
end
Queue = Thread::Queue
class Mutex
def initialize
# We still keep the @locked state so any logic based on try_lock while
# held yields reasonable results.
@locked = false
end
def lock
raise ThreadError, 'Deadlock' if @locked
@locked = true
self
end
def locked?
@locked
end
def owned?
# Being the only "thread", we implicitly own any locked mutex.
@locked
end
def try_lock
if locked?
false
else
lock
true
end
end
def unlock
raise ThreadError, 'Mutex not locked' unless @locked
@locked = false
self
end
def synchronize
lock
begin
yield
ensure
unlock
end
end
end