BEEP without holding up main program thread

Share your advanced PureBasic knowledge/code with the community.
RichardL
Enthusiast
Enthusiast
Posts: 532
Joined: Sat Sep 11, 2004 11:54 am
Location: UK

BEEP without holding up main program thread

Post by RichardL »

Code updated For 5.20+

Hardly 'advanced' but possibly uesful to someone.

My application needed a BEEP that did not hold up the main thread of the program. I wrote this procedure to manage the beep in another thread. Then I added the ability to pass the frequency and duration to the thread; and it seems quite a good way to make a beep.

Please use as you wish, at your own risk!

Run this in debug mode.
Compare the smoothness of debug messages with the normal in-line beep_() and with the beep in another thread.

Code: Select all

;     Declare Beeper(*BeeperFlag)

Procedure Beeper(*BeeperFlag) ;- Beeper that does not hold up execution of main program
  
  ; This beeper does not hold up the main program thread while it beeps
  ; ===================================================================
  ; To use it:
  
  ;   Add Procedure declaration      : Declare Beeper(*BeeperFlag)
  ;   Declare a long GLOBAL variable : BeepMe = 0
  ;   Start this thread              : CreateThread(@Beeper(),@BeepMe)
  ;   To 'Beep' set BeepMe to        : (Beeptime<<16) | BeepFreq
  
  Repeat                             ; Loop always
    Delay(1)                         ; Stop resources being grabbed by this thread
    If PeekL(*BeeperFlag)            ; If beep flag is set
      Beep_(PeekW(*BeeperFlag),PeekW(*BeeperFlag+2)); Beep...
      PokeL(*BeeperFlag,0)           ; Kill the beep flag
    EndIf
  ForEver
  
EndProcedure

; Preparation... some time before the main loop
Global BeepMe : BeepMe = 0

CreateThread(@Beeper(),@BeepMe)   ; Activate the Beeper thread

; A test loop
While 1
  Delay(1)
  
  Debug "This is a test"
  
  If (ElapsedMilliseconds() & 1000) =0
    
    ; This hogs resources
    ; Beep_(1000,200)                         
    
    ; This does NOT hog resources
    BeepMe =(200 <<16) | 1000    ; Time, Freq 
    
  EndIf
  
Wend


 
Any comments welcome.

Richard
User avatar
Hroudtwolf
Addict
Addict
Posts: 803
Joined: Sat Feb 12, 2005 3:35 am
Location: Germany(Hessen)
Contact:

Post by Hroudtwolf »

Post Reply