stevech
Joined: 23 Feb 2006
Posts: 657
|
|
Posted: 16 October 2006, 17:43 PM Post subject: task stacks with system.alloc |
|
|
I've successfully used (no memory leaks) system.alloc() to get memory for task stacks with the new 1.4 compiler/VM. I have a state machine where each state is code in a particular ZBasic sub. State transitions are done by CallTask() to startup the next state then quitting the current task (state). This scheme is what I've done in C for a long time, using function pointers though, for state machines. To me, it's easier to maintain and modify than a big switch statement. Each state (task) is a sub with a do loop that executes until the conditions arise for a state transition - wherein CallTask() changes states.
I think this general technique can be used for other than state machines, where you have tasks that are fleeting.
At the moment, I'm doing this to switch tasks:
...
callTask StateN(register.taskCurrent), system.alloc(stacksize) ' pass current stack pointer
end sub ' exit this task
Note that the stack pointer for the exiting task is passed to the new task. This permits the new task to release the stack memory for the old task:
sub StateN(byVal oldStack as unsignedInteger)
system.free(oldStack)
... compute things
end sub
----------
Of course, by design you don't system.free() stack that is a static storage item declared in a DIM. So You can have a common sub like
if (oldStack <> someStaticStack.dataAddress) then
system.free(oldStack)
end if
I've observed, but am not 100% sure, that the old task will have always exited before the system.free() is done in the new task, given the old task has no more code after the calltask(). But, I'm not sure about the case where there's a task switch just after the Calltask() causing the exit to be delayed. |
|