Fabricated system events

BlitzMax Forums/BlitzMax Module Tweaks/Fabricated system events

Kryzon(Posted 2014) [#1]
It has been noted before that user events that you post or emit from BlitzMax will not activate the WaitEvent() function, since this function only waits for system events.
This is troubling when your main thread is waiting for events with WaitEvent() and you have a child thread that wants to fire a user event - this user event would run its hooks, but it would not cause the WaitEvent() loop on the main thread to detect it and continue the program.

The following code allows you to emit a user event as if it were a system event, such that it leaves the WaitEvent() loop.
This can be called from child threads.

Save the following as "EmitEventEx.c" in the same folder as your program:
#include <brl.mod/system.mod/system.h>

static void eventExSyncOp( BBObject *event, int asyncRet ){
	
	brl_event_EmitEvent( event );

}

void EmitEventEx( int id, BBObject *source, int data, int mods, int x, int y, BBObject *extra ){
	
	BBObject *event=brl_event_CreateEvent( id, source, data, mods, x, y, extra );
	bbSystemPostSyncOp( eventExSyncOp, event, 0 );

}

And an example program of how to use the above. Make sure to build it in Multi-Threaded mode:
SuperStrict

Import "EmitEventEx.c"


Extern
		
	'This function creates and emits a user event as if it were a system event.
	'System events exit the WaitEvent() waiting loop in a way that manually emitted events with BlitzMax do not.
	
	Function EmitEventEx( id:Int, source:Object = Null, data:Int = 0, mods:Int = 0, x:Int = 0, y:Int = 0, extra:Object = Null )

End Extern


Function threadFunction:Object( data:Object )

	Delay 2000
	
	'EmitEvent( CreateEvent( EVENT_USEREVENTMASK + 1, "Generic user event test" ) ) 'Does not activate WaitEvent().
	EmitEventEx( EVENT_USEREVENTMASK + 1, "Fabricated system event test" ) 'Activates WaitEvent().
		
	Return Null

End Function



Local myThread:TThread = CreateThread( threadFunction, Null )

WaitEvent() 'Wait for a system event.

Print ""
Print String( EventSource() )

End