lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, 7 Jun 2002, Tom Wrensch wrote:

> On 7 Jun 2002, Sean Middleditch wrote:
> 
> > Yes, I meant it as a toy multi-tasker.
> 
> Hmm, well you're origional request was for cooperative multitasking. I'm
> going to assumey you are NOT talking about a system that uses timeslices
> or some such, but rather one where the various processes give up their
> turn at the processor by calling some particular routine.
> 
> If that's the case then it should be a simple matter to build a process
> scheduler that turns this "toy" into a true cooperative multitasking
> system.
> 

And here it is. Of course this is only for cooperative multiprocessing. So
you have to put yield calls in your code. This is pretty easy if you have
some library routines that are called all the time, just put the yield
calls in those.

Anyway, I hope this is useful to somebody.

  - Tom Wrensch


-- -------------------------------------------------
-- Simple scheduler for cooperative multitasking 
-- using Lua 5.0w0's coroutines
-- 
-- To use:
-- New tasks are scheduled using the scheduleTask
-- function:
--
--     scheduleTask(function() ...code here... end)
--
-- Inside the code of your task, you will need to 
-- call coroutine.yield() to give up the processor
-- time.
-- 
-- To start the scheduler, execute this function:
--
--     runScheduler()
--
-- This function will return once all tasks have
-- completed.
--
-- Note that you will have to add at least one task
-- before running the scheduler, or it will simply
-- return without doing anything.
-- -------------------------------------------------


tasks = {}

function scheduleTask(func)
    table.insert(tasks, coroutine.create(func))    
end

function removeTask(t)
    local i=1
    while i<=table.getn(tasks) and tasks[i]~=t do
        i=i+1
    end
    if tasks[i]==t then
        table.remove(tasks,i)
    end
end

function runScheduler()
    while table.getn(tasks) > 0 do
        for i=1,table.getn(tasks) do
            local task=tasks[i]
            if type(task)=="function" then
                if not pcall(task) then
                    removeTask(task)
                end
            end
        end
    end
end


-- --------------------------------------------------
-- A simple set of functions, each of which will
-- be used as the root of a thread.
--
-- To run the example, call runScheduler()
-- --------------------------------------------------

function task1()
  for i=1,5 do 
      print(i) 
      coroutine.yield()
  end
end

function task2()
    for i=6,12 do 
        print(i) coroutine.yield()
    end 
end

function task3() print("goodbye") end

function task4() 
    for i=1,6 do 
        print("hello")
        scheduleTask(task3)
        coroutine.yield()
    end 
end


-- Add the tasks to the scheduler
scheduleTask(task1)
scheduleTask(task2)
scheduleTask(task4)

-- Now do it
-- runScheduler()