summaryrefslogtreecommitdiff
path: root/xmake/core/thread/thread.lua
blob: dcb74e28204cf26ea401c9376bce750487c8a8b7 (plain)
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
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author      ruki
-- @file        thread.lua
--

-- define module
local thread      = thread or {}
local _instance   = _instance or {}

-- load modules
local io      = require("base/io")
local libc    = require("base/libc")
local bytes   = require("base/bytes")
local table   = require("base/table")
local string  = require("base/string")
local sandbox = require("sandbox/sandbox")

-- the thread status
thread.STATUS_READY     = 1
thread.STATUS_RUNNING   = 2
thread.STATUS_SUSPENDED = 3
thread.STATUS_DEAD      = 4

-- new a thread
function _instance.new(callback, opt)
    opt = opt or {}
    local instance = table.inherit(_instance)
    instance._NAME      = opt.name or "anonymous"
    instance._ARGV      = opt.argv
    instance._CALLBACK  = callback
    instance._STACKSIZE = opt.stacksize or 0
    instance._STATUS    = thread.STATUS_READY
    setmetatable(instance, _instance)
    return instance
end

-- get thread name
function _instance:name()
    return self._NAME
end

-- get cdata of thread
function _instance:cdata()
    return self._HANLDE
end

-- get thread status
function _instance:status()
    return self._STATUS
end

-- is ready?
function _instance:is_ready()
    return self:status() == thread.STATUS_READY
end

-- is running?
function _instance:is_running()
    return self:status() == thread.STATUS_RUNNING
end

-- is suspended?
function _instance:is_suspended()
    return self:status() == thread.STATUS_SUSPENDED
end

-- is dead?
function _instance:is_dead()
    return self:status() == thread.STATUS_DEAD
end

-- start thread
function _instance:start()
    if not self:is_ready() then
        return nil, string.format("%s: cannot start non-ready thread!", self)
    end
    assert(not self:cdata())

    -- serialize and pass callback and arguments to this thread
    -- we do not use string.serialize to serialize callback, because it's slower (deserialize)
    local callinfo = string._dump(self._CALLBACK, true)
    local argv = self._ARGV
    if argv ~= nil then
        callinfo = string.serialize(argv, {strip = true, indent = false}) .. "<Argv\27>" .. callinfo
    end

    -- init and start thread
    local handle, errors = thread.thread_init(self:name(), callinfo, self._STACKSIZE)
    if not handle then
        return nil, errors or string.format("%s: failed to create thread!", self)
    end

    self._HANLDE = handle
    self._STATUS = thread.STATUS_RUNNING
    return true
end

-- suspend thread
function _instance:suspend()
    if not self:is_running() then
        return nil, string.format("%s: cannot suspend non-running thread!", self)
    end
    assert(self:cdata())

    local ok, errors = thread.thread_suspend(self:cdata())
    if not ok then
        return nil, errors or string.format("%s: failed to suspend thread!", self)
    end

    self._STATUS = thread.STATUS_SUSPENDED
    return true
end

-- resume thread
function _instance:resume()
    if not self:is_suspended() then
        return nil, string.format("%s: cannot suspend non-suspended thread!", self)
    end
    assert(self:cdata())

    local ok, errors = thread.thread_resume(self:cdata())
    if not ok then
        return nil, errors or string.format("%s: failed to resume thread!", self)
    end

    self._STATUS = thread.STATUS_RUNNING
    return true
end

-- wait thread
function _instance:wait(timeout)
    if self:is_dead() then
        return 1
    elseif self:is_ready() then
        return -1, string.format("%s: cannot wait ready thread!", self)
    end
    assert(self:cdata())

    local ok, errors = thread.thread_wait(self:cdata(), timeout)
    if ok < 0 then
        return -1, errors or string.format("%s: failed to resume thread!", self)
    end

    if ok > 0 then
        self._STATUS = thread.STATUS_DEAD
    end
    return ok
end

-- tostring(thread)
function _instance:__tostring()
    local status_strs = self._STATUS_STRS
    if not status_strs then
        status_strs = {
            [thread.STATUS_READY]     = "ready",
            [thread.STATUS_RUNNING]   = "running",
            [thread.STATUS_SUSPENDED] = "suspended",
            [thread.STATUS_DEAD]      = "dead"
        }
        self._STATUS_STRS = status_strs
    end
    return string.format("<thread: %s/%s>", self:name(), status_strs[self:status()])
end

-- gc(thread)
function _instance:__gc()
    if self:cdata() and self:is_dead() and io.thread_exit(self:cdata()) then
        self._HANLDE = nil
    end
end

-- new a thread
--
-- @param callback      the thread callback
-- @param opt           the thread options, e.g. {name = "", argv = {}, stacksize = 8192}
--
-- @return the thread instance
--
function thread.new(callback, opt)
    if callback == nil then
        return nil, "invalid thread, callback is nil"
    end
    return _instance.new(callback, opt)
end

-- get the running thread
function thread.running()
    -- TODO
end

-- run thread
function thread._run_thread(callinfo_str)

    -- get callinfo
    local parts = callinfo_str:split("<Argv\27>", {plain = true})
    local callback_str, argv_str
    if #parts > 1 then
        callback_str = parts[2]
        argv_str = parts[1]
    else
        callback_str = parts[1]
    end

    -- load callback
    local fenv = debug.getfenv(debug.getinfo(2, "f").func)
    local callback
    if callback_str then
        local script, errors = load(callback_str, "=(thread)", "b", fenv)
        if not script then
            return false, string.format("cannot load thread callback, %s!", errors or "unknown")
        end
        --[[
        for i = 1, math.huge do
            local upname, upvalue = debug.getupvalue(script, i)
            if upname == nil or upname == "" then
                break
            end
            print("upname", i, upname, upvalue)
        end]]
        callback = script
    end
    if not callback then
        return false, "no thread callback"
    end

    -- load argument list
    local argv
    if argv_str then
        local result, errors = string.deserialize(argv_str)
        if not result then
            return false, string.format("invalid thread arguments, %s!", errors or "unknown")
        end
        argv = result
    end

    -- bind sandbox
--    local sandbox_inst, errors = sandbox.new(callback, {
--        filter = interp:filter(), rootdir = interp:rootdir(), namespace = interp:namespace()})
    local sandbox_inst, errors = sandbox.new(callback)
    if not sandbox_inst then
        return false, errors
    end

    -- do callback
    return sandbox.load(sandbox_inst:script(), table.unpack(argv or {}))
end

-- return module
return thread