Android Question "wait for" and variable change

irda

Member
Licensed User
Longtime User
Hello everybody.
Is it possible to use "resumable subs" using a variable?
That is, blocking a function waiting for a variable to change state (in another function). Something like :

B4X: Copy
mysemaphore = false
'Wait'
waitfor(mysemaphore = true)
'continue'

In other projects I have used "Lock" type variables from an external library ("threading") but I am looking for something more standard.

Thanks for all!
 
Why do you need this? As your code all runs in the single main thread (unless you are using threads in which case Lock is the best solution) then whatever clears the semaphore can just call the required code. If you wanted a bit of flexibility in what gets called when the semaphore clears you could maintain an array of Sub names and use CallSub to invoke them in turn like C# Delegates do.
 
Upvote 0
B4X: Copy
Sub FirstSub
    Log("FirstSub started")
    SecondSub
    Wait For SecondSub_Complete
    Log("FirstSub completed")
End Sub


Sub SecondSub
    Log("SecondSub started")
   Do Until mysemaphore ....
        '....
    Loop
    Log("SecondSub completed")
    CallSubDelayed(Me, "SecondSub_Complete")
End Sub
 
Upvote 0
That will not work. Looping to wait on something is always a bad idea. It burns power and CPU cycles unnecessarily.

Do Until mysemaphore ....
'....
Loop


This loop will block the main thread and whatever clears the semaphore will never get run, unless it is on a separate thread in which case Lock is the correct solution.

Also you can only wait on an event or a Resumable Sub which SecondSub is not.
 
Upvote 0
Upvote 0
Thanks for the answers.
My need comes because I have to interrogate multiple asynchronous devices. It may take time to answer, but I can't go on to the next one until I have received the answer from the first one. Meanwhile, other status frames may arrive.
Erel's solution would almost solve the problem. I am considering using a timer and checking what responses I have received before moving on to the next question.
 
Upvote 0
Back
Top