test3.monkey2 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #Rem
  2. Little demo showing how to add things to a queue for a thread to process.
  3. #End
  4. Namespace myapp
  5. #Import "<std>"
  6. #Import "<mojo>"
  7. #Import "<thread>"
  8. Using std..
  9. Using mojo..
  10. Class MyWindow Extends Window
  11. Field _queue:=New IntDeque
  12. Field _mutex:=New Mutex
  13. Field _sema:=New Semaphore
  14. Field _sent:Int
  15. Field _recv:Int
  16. Method New( title:String="Simple mojo app",width:Int=640,height:Int=480,flags:WindowFlags=Null )
  17. Super.New( title,width,height,flags )
  18. 'Create background thread and detach it.
  19. New Thread( Lambda()
  20. Repeat
  21. 'Wait for something to be added to queue.
  22. _sema.Wait()
  23. 'Remove next item from the queue - the mutex protects against concurrent modification.
  24. _mutex.Lock()
  25. Local item:=_queue.RemoveFirst()
  26. _mutex.Unlock()
  27. _recv+=item
  28. Forever
  29. End ).Detach()
  30. End
  31. Method OnRender( canvas:Canvas ) Override
  32. App.RequestRender()
  33. 'Adds a random number of items to the queue.
  34. For Local i:=0 Until Int( Rnd(5)+5 )
  35. 'Each item is just a random int.
  36. Local item:=Int( Rnd( 5 ) )
  37. _sent+=item
  38. 'Add item to the queue - the mutex protects against concurrent modification.
  39. _mutex.Lock()
  40. _queue.AddLast( item )
  41. _mutex.Unlock()
  42. 'Signal thread there's something new to be removed.
  43. _sema.Signal()
  44. Next
  45. 'Easier to check difference - recv should equal sent but with a lag.
  46. Local diff:=_sent-_recv
  47. canvas.DrawText( "Sent="+_sent+", Received="+_recv+", Difference="+diff,Width/2,Height/2,.5,.5 )
  48. End
  49. End
  50. Function Main()
  51. New AppInstance
  52. New MyWindow
  53. App.Run()
  54. End