

  '================================================
  'MULTIPLE THREADS WITH SYNC FOR STRING PROCESSING
  '================================================

  uses MinWin

  #define INFINITE 0xFFFFFFFF  //Infinite timeout


  sys eventA,eventB,MaxSimult
  sys busy,entries

  bstring s[8]<=("String A:" cr,"string B:" cr,"string C:" cr)


  '-----------------------
  function append(sys i,c)
  '=======================
  'do
  '  if busy then inc eventB : sleep 1 : else busy=1 : exit do
  'end do
  '
  inc entries
  '
  'add asci char to indexed string
  '
  sys a,b,le,p
  p=@s
  mov ecx,i
  dec ecx
  shl ecx,2 'array index
  add ecx,p
  mov a,ecx 'bstring location
  mov ecx,[ecx]
  mov eax,[ecx-4]
  mov le,eax
  add le,1
  b=getmemory le
  copy b,*a,le
  mov ecx,b
  add ecx,le
  dec ecx
  mov al,c
  mov [ecx],al
  freememory *a
  *a=b
  '
  dec entries
  if entries then inc eventB
  if maxSimult<entries then MaxSimult=entries
  busy=0
  '
  end function

  '-------------------------------------------
  function ThreadA( sys n ) as sys external
  '===========================================
  finit
  sys i=65,j
  do
    append 1,i
    inc eventA
    inc i
    sleep 1
    if i>90 then i=65 : inc j : if j=4 then exit do
  end do
  return 0
  end function 

  '-------------------------------------------
  function ThreadB( sys n ) as sys external
  '===========================================
  finit
  sys i=97,j
  do
   append 2,i
   inc eventA
    inc i
    sleep 1
    if i>122 then i=97 : inc j : if j=4 then exit do
  end do
  return 0
  end function 

  '-------------------------------------------
  function ThreadC( sys n ) as sys external
  '===========================================
  finit
  sys i=48,j
  do
    append 3,i
    inc eventA
    inc i
    sleep 1
    if i>57 then i=48 : inc j : if j=8 then exit do
  end do
  return 0
  end function 


  '--------------------------
  function together(sys n,*f)
  '==========================
  '
  sys  hThread[64], Id[64], i,p,d
  '
  '
  'Create the thread to begin execution on its own.
  '------------------------------------------------
  '
  for i=1 to n
    p=f[i] : d=@Id[i]
    hThread[i] =  CreateThread 0,0,p,i,0,d
  next
  '
  WaitForMultipleObjects n, @hThread, 1, INFINITE
  '
  '
  for i=1 to n
    CloseHandle hThread[i]
  next
  '
  end function

  '
  '====
  'TEST
  '====
  '
  sys procs[64]
  procs<=@ThreadA, @ThreadB, @ThreadC
  together 3, procs
  '
  string pr

  pr=s[1] cr s[2] cr s[3] cr cr "String Ops: " EventA cr+
  "Total Parallel Encounters: " EventB cr+
  "Max string operations in parallel: " MaxSimult
  '
  frees s[1]
  frees s[2]
  frees s[3]

  'putfile "t.txt",pr
  print pr



