Updating gadget from thread

Just starting out? Need help? Post your questions and find answers here.
firace
Enthusiast
Enthusiast
Posts: 727
Joined: Wed Nov 09, 2011 8:58 am

Updating gadget from thread

Post by firace »

I need to frequently update the value of a textgadget without blocking the event loop. Is this an acceptable / simple way of doing it? (Thread, PostEvent, and a shared variable)

Code: Select all


Procedure Watcher1(*x)
  Shared cBlock.s
  
  Repeat  
    cBlock.s = Str(Random(999999))
    PostEvent(999)
    Delay(550)
  ForEver
  
EndProcedure


OpenWindow(0, 100, 20, 820, 310, "Dashboard 5")

ButtonGadget(8, 20,     270, 200, 24, "Test 1")
TextGadget(333, 750,    270, 140, 28, "...")

CreateThread(@Watcher1(), 0)

Repeat
  e = WaitWindowEvent()
  Select e
    Case  999 :      SetGadgetText(333, cBlock)
    Case  #PB_Event_CloseWindow : End
  EndSelect
ForEver

BarryG
Addict
Addict
Posts: 1706
Joined: Thu Apr 18, 2019 8:17 am

Re: Updating gadget from thread

Post by BarryG »

The manual says that's what PostEvent() is for... so, yes.
User avatar
mk-soft
Addict
Addict
Posts: 3190
Joined: Fri May 12, 2006 6:51 pm
Location: Germany

Re: Updating gadget from thread

Post by mk-soft »

Under Windows, it sometimes works directly from threads. Activate compiler option Threadsafe.
Under Linux and macOS this leads to a crash of the programme.

See "ThreadToGUI" signature
My Projects ThreadToGUI / OOP-BaseClass / OOP-BaseClassDispatch / EventDesigner V3
PB v3.30 / v5.70 - OS Mac Mini OSX 10.xx - VM Window Pro / Linux Ubuntu
Downloads on my Webspace
#NULL
Addict
Addict
Posts: 1364
Joined: Thu Aug 30, 2007 11:54 pm
Location: right here

Re: Updating gadget from thread

Post by #NULL »

You would still have to protect cBlock with a mutext or something.
infratec
Always Here
Always Here
Posts: 5518
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Updating gadget from thread

Post by infratec »

Why a shared variable?

If you do such things you ned a semaphore, to guarantee that the variable is not overwritten by the thread.
For a numeric variable, you can use PostEvent(..., data) and EventData() :wink:
Post Reply