
'CALLS FOR MULTITHREADING ETC

library "kernel32.dll"
sys   CreateThread (sys lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, *lpThreadId)
dword WaitForMultipleObjects(sys nCount,*lpHandles, bWaitAll, dwMilliseconds)
bool  CloseHandle(sys hObject)
void  Sleep(sys dwMilliSeconds)
library ""

% INFINITE 0xFFFFFFFF  'Infinite timeout


'COMMUNICATION SYSTEM
'====================

indexbase 1

% Threads          16 'including controller
% MsgNone          0
% MsgSlow          1
% MsgFast          2
% MsgHello         42
% MsgTerminate     255
'
% MsgFromCtrler    n*threads
% MsgFromA         n*threads+1
% MsgFromB         n*threads+2
'...
% MsgToCtrler      n
% MsgToA           1*threads+n
% MsgToB           2*threads+n
'...


sys signal[threads*threads] 'communications table


'THREAD FUNCTIONS

function threadA(sys n) external
finit
do
  if signal[MsgFromCtrler]=MsgTerminate then exit do
  signal[MsgToCtrler]=MsgHello
  sleep 1
end do
print "A terminated " n
end function

function threadB(sys n) external
finit
do
  if signal[MsgFromCtrler]=MsgTerminate then exit do
  signal[MsgToCtrler]=MsgHello
  sleep 1
end do
print "B terminated " n
end function

sys Funs[threads]={@threadA,@threadB}, ThreadsRunning=2

'START THREADS

sys  hThread[threads], id[threads], i, n
'
for i=1 to threadsRunning
  hThread[ i ] =  CreateThread 0,0,funs[ i ],i,0,id[ i ]
next


'CHECK FOR HELLO MESSAGES

sleep 10 'wait for threads to activate

print "Running: " signal[MsgFromA] "," signal[MsgFromB]


'END THREADS

signal[MsgToA]=MsgTerminate
signal[MsgToB]=MsgTerminate

WaitForMultipleObjects ThreadsRunning, hThread, 1, INFINITE

for i=1 to ThreadsRunning
  CloseHandle hThread[ i ]
next

