Skip to content

Add native thread support #6755

@waruqi

Description

@waruqi

Currently, the thread/event/mutex waiting interface does not support coordinated scheduling with coroutines, but this support will be further improved in the future.

Use mutex

import("core.base.thread")

function callback(mutex)
    import("core.base.thread")
    print("%s: starting ..", thread.running())
    local dt = os.mclock()
    for i = 1, 10 do
        mutex:lock()
        print("%s: %d", thread.running(), i)
        mutex:unlock()
        os.sleep(1000)
    end
    dt = os.mclock() - dt
    print("%s: end, dt: %d ms", thread.running(), dt)
end

function main()
    local mutex = thread.mutex()
    local t0 = thread.start_named("thread_0", callback, mutex)
    local t1 = thread.start_named("thread_1", callback, mutex)
    t0:wait(-1)
    t1:wait(-1)
end

Use event

import("core.base.thread")

function callback(event)
    import("core.base.thread")
    print("%s: starting ..", thread.running())
    while true do
        print("%s: waiting ..", thread.running())
        if event:wait(-1) > 0 then
            print("%s: triggered", thread.running())
        end
    end
end

function main()
    local event = thread.event()
    local t = thread.start_named("keyboard", callback, event)
    while true do
        local ch = io.read()
        if ch then
            event:post()
        end
    end
    t:wait(-1)
end

Use semaphore

import("core.base.thread")

function callback(semaphore)
    import("core.base.thread")
    print("%s: starting ..", thread.running())
    while true do
        print("%s: waiting ..", thread.running())
        if semaphore:wait(-1) > 0 then
            print("%s: triggered", thread.running())
        end
    end
end

function main()
    local semaphore = thread.semaphore("", 1)
    local t = thread.start_named("keyboard", callback, semaphore)
    while true do
        local ch = io.read()
        if ch then
            semaphore:post(2)
        end
    end
    t:wait(-1)
end

Use queue to pass shared data

import("core.base.thread")

function callback(event, queue)
    print("starting ..")
    while true do
        print("waiting ..")
        if event:wait(-1) > 0 then
            while not queue:empty() do
                print("  -> %s", queue:pop())
            end
        end
    end
end

function main()
    local event = thread.event()
    local queue = thread.queue()
    local t = thread.start_named("", callback, event, queue)
    while true do
        local ch = io.read()
        if ch then
            queue:push(ch)
            event:post()
        end
    end
    t:wait(-1)
end

#6324

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions