createsemaphore.bmx 679 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'Make sure to have 'Threaded build' enabled!
  2. '
  3. Strict
  4. 'a simple queue
  5. Global queue$[100],put,get
  6. 'a counter semaphore
  7. Global counter:TSemaphore=CreateSemaphore( 0 )
  8. Function MyThread:Object( data:Object )
  9. 'process 100 items
  10. For Local item=1 To 100
  11. 'add an item to the queue
  12. queue[put]="Item "+item
  13. put:+1
  14. 'increment semaphore count.
  15. PostSemaphore counter
  16. Next
  17. End Function
  18. 'create worker thread
  19. Local thread:TThread=CreateThread( MyThread,Null )
  20. 'receive 100 items
  21. For Local i=1 To 100
  22. 'Wait for semaphore count to be non-0, then decrement.
  23. WaitSemaphore counter
  24. 'Get an item from the queue
  25. Local item$=queue[get]
  26. get:+1
  27. Print item
  28. Next