Coroutines in DOS, in pure FreeBasic

DOS specific questions.
Post Reply
angros47
Posts: 2326
Joined: Jun 21, 2005 19:04

Coroutines in DOS, in pure FreeBasic

Post by angros47 »

This is a port of the code I mentioned here https://freebasic.net/forum/viewtopic.php?f=17&t=28417

Code: Select all

static shared co_active_buffer(63) as long
static shared co_active_handle as any ptr

sub co_swap Naked __fastcall(a as any ptr, b as any ptr)
asm
	mov [edx],esp    
	mov esp,[ecx]    
	pop eax          
	mov [edx+ 4],ebp 
	mov [edx+ 8],esi 
	mov [edx+12],edi 
	mov [edx+16],ebx 
	mov ebp,[ecx+ 4] 
	mov esi,[ecx+ 8] 
	mov edi,[ecx+12] 
	mov ebx,[ecx+16] 
	jmp eax          
end asm
end sub


function co_active() as any ptr
	if co_active_handle=0 then co_active_handle = @co_active_buffer(0)
	return co_active_handle
end function

function co_derive(memory as any ptr, size as unsigned long, entrypoint as sub()) as any ptr
	dim handle as any ptr
	if co_active_handle=0 then co_active_handle = @co_active_buffer(0)

	handle = memory
	dim offset as unsigned long = (size and not 15) - 32
	dim p as long ptr = cast(long ptr,cast(ubyte ptr,handle) + offset)  ' seek to top of stack 
	p-=2
	'*--p = (long)crash;                         /* crash if entrypoint returns */
	*p = cast(long,entrypoint)                    ' start of function 
	*cast(long ptr,handle) = cast(long, p)        ' stack pointer 


	return handle
end function

function co_create(size as unsigned long, entrypoint as sub()) as any ptr
	dim memory as any ptr = allocate(size)
	if memory=0 then return 0
	return co_derive(memory, size, entrypoint)
end function

sub co_switch(handle as any ptr) 
	dim as any ptr co_previous_handle = co_active_handle
	co_active_handle=handle
	co_swap(handle, co_previous_handle)
end sub









dim shared as any ptr t0,t1

sub task
	dim z as integer
	do
		z+=1
		print "this is the thread, iteration ";z
		co_switch(t0)
	loop

end sub




t0=co_active()
t1=co_create(65536,@task)


for i as integer=1 to 50
	print "this is main"
	co_switch(t1)
next
I publish it under DOS since it's the version specific for x86 32 bit
Post Reply