PurpleSkyHoliday
PurpleSkyHoliday

Reputation: 109

Getting a second thread to update consistently?

I'm trying to create a "heartbeat monitor" of sorts in autohotkey.

My current program is simple, i have a process that takes about 2 seconds to complete to calculate how sharp the beeps should be, and a small looping routine that beeps at the calculated frequency.

But I've now run into a roadblock - How can I update the "beeper" routine to use the new frequency without interrupting it's regular timing?

What i initially tried was effectively checking global variables (which i felt would be unlikely to work)

frequency := 500 ;super-global default frequency

Somehotkey::
SetTimer, BeepCycle, -1
Loop, 
{
   frequency := CalculateFrequency()
   Sleep, 5000
}
return

BeepCycle:
loop,
{
   SoundBeep, %frequency%
   Sleep, 500
}

but the frequency seems to just never update (because calculatefrequency never runs again), which makes some sense.

So my next approach was to use the timing of settimer instead, but it's simply nowhere near consistent enough.

frequency := 500 ;super-global default frequency

Somehotkey::
SetTimer, BeepCycle, 500
Loop, 
{
   frequency := CalculateFrequency()
   Sleep, 5000
}
return

BeepCycle:
SoundBeep, %frequency%

Whats the best way to allow changing of the frequency while keeping the 500ms breaks consistent? I'm new to multithreading in ahk.

Upvotes: 0

Views: 49

Answers (1)

PurpleSkyHoliday
PurpleSkyHoliday

Reputation: 109

Credit to wolf_II on the autohotkey forums - here's the best solution i've found so far.

Using two timers allows them to play nicer with eachother (and avoids the sleeping issue from the comments)

global frequency := 500 ; default frequency

Somehotkey::
SetTimer, BeepCycle, 500
SetTimer, CalcCycle, 5000
return

BeepCycle:
   SoundBeep, %frequency%
return


CalcCycle:
   frequency := CalculateFrequency()
return

Upvotes: 1

Related Questions