createmutex.bmx 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'Make sure to have 'Threaded build' enabled!
  2. '
  3. Strict
  4. 'a global list that multiple threads want to modify
  5. Global list:TList=New TList
  6. 'a mutex controlling access to the global list
  7. Global listMutex:TMutex=CreateMutex()
  8. Function MyThread:Object( data:Object )
  9. For Local item=1 To 10
  10. 'simulate 'other' processing...
  11. Delay Rand( 10,50 )
  12. 'lock mutex so we can safely modify global list
  13. LockMutex listMutex
  14. 'modify list
  15. list.AddLast "Thread "+data.ToString()+" added item "+item
  16. 'unlock mutex
  17. UnlockMutex listMutex
  18. Next
  19. End Function
  20. Local threads:TThread[10]
  21. 'Create worker threads
  22. For Local i=0 Until 10
  23. threads[i]=CreateThread( MyThread,String( i+1 ) )
  24. Next
  25. Print "Waiting for worker threads..."
  26. 'Wait for worker threads to finish
  27. For Local i=0 Until 10
  28. WaitThread threads[i]
  29. Next
  30. 'Show the resulting list
  31. '
  32. 'Note: We don't really have to lock the mutex here, as there are no other threads running.
  33. 'Still, it's a good habit to get into.
  34. LockMutex listMutex
  35. For Local t$=EachIn list
  36. Print t
  37. Next
  38. UnlockMutex listMutex