07-22-2008, 09:43 AM
Took me a while to figure out but here is what i came up with, hopefully will help someone else. In this example only one thread can be working at a time, so the others wait their turn.
Output Example
Macro
Function threading_main
Function threading_getlock
Function threading_releaselock
Function threading_islocked
Function threading_waitfor_release
Function formatmsg
Output Example
07/22/2008 02:32:59 [8s] : [876] Locking thread
07/22/2008 02:32:59 [0s] : [1288] waiting for unlock 876
07/22/2008 02:32:59 [0s] : [628] waiting for unlock 876
07/22/2008 02:33:07 [8s] : [876] Releasing thread
07/22/2008 02:33:07 [0s] : [628] Locking thread
07/22/2008 02:33:15 [8s] : [628] Releasing thread
07/22/2008 02:33:15 [0s] : [1288] Locking thread
07/22/2008 02:33:17 [2s] : [876] waiting for unlock 1288
07/22/2008 02:33:23 [6s] : [1288] Releasing thread
07/22/2008 02:33:23 [0s] : [876] Locking thread
07/22/2008 02:33:25 [2s] : [628] waiting for unlock 876
07/22/2008 02:33:31 [6s] : [876] Releasing thread
07/22/2008 02:33:31 [0s] : [628] Locking thread
07/22/2008 02:33:33 [2s] : [1288] waiting for unlock 628
// Main script, starts three threads
int+ control_locked = 0
int+ control_locked_by = 0
mac("threading_main")
mac("threading_main")
mac("threading_main")
function
QMTHREAD thread
GetQmThreadInfo 0 &thread
int tid = thread.threadid
int thandle = thread.threadhandle
int+ control_locked;
int+ control_locked_by;
rep
,;locking
,if(control_locked)
,,threading_waitfor_release(thandle)
,,goto locking
,else
,,formatmsg("Locking thread" thandle)
,,threading_getlock(thandle)
,,wait 8
,,formatmsg("Releasing thread" thandle)
,,threading_releaselock(thandle)
,,,
,wait 10
function int'thread_id
int+ control_locked
int+ control_locked_by
if(!control_locked)
,control_locked = 1
,control_locked_by = thread_id
,ret 1
ret 0
function int'thread_id
int+ control_locked
int+ control_locked_by
if(control_locked)
,if(control_locked_by == thread_id)
,,control_locked = 0
,,control_locked_by = 0
,,ret 1
,else
,,formatmsg("Only the control owner can release thread control" thread_id)
else
,formatmsg("control isnt locked" thread_id)
,
ret 0
Function threading_waitfor_release
function int'thread_id
int+ control_locked
int+ control_locked_by
if(control_locked)
,formatmsg(_s.from("waiting for unlock " control_locked_by) thread_id)
,wait 0 -V control_locked
,
ret 1
// Formats debug messages with timestamp
function str'msg [str'c]
// Compare last message time and time now
DATE+ lastmessage_time
DATE now = now.getclock
SYSTEMTIME st
now.diff(lastmessage_time st 2)
lastmessage_time = now
// Calculate and save time passed since last action
int+ lastmessage_elapsed = st.wHour*3600 + st.wMinute*60 + st.wSecond
// Output log message
if(c.len>1) c=_s.from("["c "] ")
out _s.from(_s.time("MM/dd/yyyy" "HH:mm:ss") " [" lastmessage_elapsed "s]" " : " c msg)