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:
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!
 

agraham

Expert
Licensed User
Longtime User
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

MarcoRome

Expert
Licensed User
Longtime User
B4X:
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

agraham

Expert
Licensed User
Longtime User
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

Erel

B4X founder
Staff member
Licensed User
Longtime User
CallSubDelayed(Me, "SecondSub_Complete")
Such code was needed in the very first version of resumable subs. Much better to use this feature now: [B4X] Resumable subs that return values (ResumableSub)

You can wait for a value, and it is useful in some cases:
B4X:
Do While SomeCondition
Sleep(100)
Loop
It won't lock the main thread and won't require more power than a timer that fires every 100ms.
 
Upvote 0

irda

Member
Licensed User
Longtime User
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
Top