开发者

Task scheduling - controlling the execution of a function

开发者 https://www.devze.com 2023-02-19 02:04 出处:网络
In an embedded project, we\'re supposed to implement a task scheduler with different priorities, the project implementation is in C and is run on an Arduino device.

In an embedded project, we're supposed to implement a task scheduler with different priorities, the project implementation is in C and is run on an Arduino device.

Now that we're in the researching phase, one question popped but nobody had experience enough to have a certain answer:

How is it possible to control the execution time of a function? How do we keep track of time before the function returns so we can interrupt it for example when a time-out occurs?

One suggestion was to use fork(), but sin开发者_开发问答ce Arduino does not include an operation system, there's no kernel to handle a thread. Or am I wrong?

Any input will be helpful, thanks a bunch,


You need a timer. All non-cooperative multi tasking systems (i.e. those which don't depend on the function to say "you can interrupt me now" all the time) use a timer to stop the execution after some time (say 100ms).

In the interrupt handler, check if there is another "thread" which can run and switch context.

A pretty simple implementation is a "ready list": Whenever a task or thread could do some work, add it to the ready list.

When the timer fires, add the current task at the end of the list and make the head of the list the current task.


In an embedded system a task scheduler is the core of an operating system (usually an RTOS), so you are being asked to implement one not to use one.

A simple example of how such a scheduler works is described in Jean Labrosse's boot Micro C/OS-II. It describes a complete RTOS kernel with scheduling and IPC. For your project you can take the description of this core and implement your own (or you could use the included source code).

Such a kernel works by scheduling at certain OS calls and on a timer interrupt. A context switch involves storing the processor registers for one task and replacing then with teh registers for another. Because this register save/restore includes the stack-pointer and program counter, control is switched between threads.

It may be that simpler forms of scheduling (rather than preemptive) scheduling are called for. One method is to implement task functions that run to completion and where necessary store their own state and are implemented as state-machines, and then have a simple loop that polls a timer and call's each 'task' function according to a schedule table (that includes the periodicity of the task and a pointer to its function, so that say one function will be called every second, while another will be called every millisecond.

0

精彩评论

暂无评论...
验证码 换一张
取 消