Triggering action from another thread

Started by ingar, 05 May 2019, 09:25:23

ingar

Hi,

In my app I have a thread that checks if an RFID card is placed over an RFID reader. If a card is detected the app reads some data from the card. This data I would like to pass to an event handler in my main thread. Q: What's the best method for doing this in tgui?

I Windows programming, the thread typically issues a PostMessage to the main window thread, and the message handler in the main thread does the handling.

Regards,
Ingar

texus

You can't access the same SFML or TGUI objects from multiple threads at the same time, it is up to you to do the synchronization. One way would be to use mutexes around the TGUI objects you access, but that will likely decrease performance as you would have to lock practically everywhere in the main thread (locks around both event handling and drawing and anywhere else where you access TGUI widgets). So the best way is probably to only let the main thread access TGUI and get your data to the main thread somehow. How to do this is of course not related to TGUI.

I don't have much experience with syncing between threads myself, other than on a windows-only project that uses the Windows functions like PostMessage, SetEvent and WaitForSingleObject.
A pure c++ alternative to SetEvent/WaitForSingleObject would probably be to have a mutex around a shared variable. Every frame (or every X milliseconds) you lock the mutex, check the variable and unlock the mutex again. In the other thread, when data is read from the card, it locks the mutex, writes the data in the variable and unlock the mutex again.

ingar

Hi again,

OK. I can do a mutex. And probably call a function to handle the external event from the main event loop.

Thanks,
Ingar


Quote from: texus on 05 May 2019, 09:51:09
You can't access the same SFML or TGUI objects from multiple threads at the same time, it is up to you to do the synchronization. One way would be to use mutexes around the TGUI objects you access, but that will likely decrease performance as you would have to lock practically everywhere in the main thread (locks around both event handling and drawing and anywhere else where you access TGUI widgets). So the best way is probably to only let the main thread access TGUI and get your data to the main thread somehow. How to do this is of course not related to TGUI.

I don't have much experience with syncing between threads myself, other than on a windows-only project that uses the Windows functions like PostMessage, SetEvent and WaitForSingleObject.
A pure c++ alternative to SetEvent/WaitForSingleObject would probably be to have a mutex around a shared variable. Every frame (or every X milliseconds) you lock the mutex, check the variable and unlock the mutex again. In the other thread, when data is read from the card, it locks the mutex, writes the data in the variable and unlock the mutex again.