blockingqueue_02.bmx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. '
  2. ' Demonstrates how to use a blocking queue to synchronize threads.
  3. '
  4. SuperStrict
  5. Framework Brl.StandardIO
  6. Import Brl.Threads
  7. Import Brl.Collections
  8. Function Producer:Object(data:Object)
  9. Local queue:TBlockingQueue<Int> = TBlockingQueue<Int>(data)
  10. For Local i:Int = 1 To 10
  11. Try
  12. Print "Producing " + i
  13. queue.Enqueue(i, 100, ETimeUnit.Milliseconds) ' 100 milliseconds timeout
  14. Delay 100 ' Simulate work
  15. Catch ex:TTimeoutException
  16. Print "Enqueue timed out: " + ex.ToString()
  17. End Try
  18. Next
  19. End Function
  20. Function Consumer:Object(data:Object)
  21. Local queue:TBlockingQueue<Int> = TBlockingQueue<Int>(data)
  22. For Local i:Int = 1 To 10
  23. Try
  24. Local item:Int = queue.Dequeue(1500, ETimeUnit.Milliseconds) ' 1.5 second timeout
  25. Print "Consuming " + item
  26. Delay 1000 ' Simulate work
  27. Catch ex:TTimeoutException
  28. Print "Dequeue timed out: " + ex.ToString()
  29. End Try
  30. Next
  31. End Function
  32. Local queue:TBlockingQueue<Int> = New TBlockingQueue<Int>(5)
  33. Local producerThread:TThread = CreateThread(Producer, queue)
  34. Local consumerThread:TThread = CreateThread(Consumer, queue)
  35. WaitThread(producerThread)
  36. WaitThread(consumerThread)
  37. Print "All tasks are done."