I am developing an application library using GTK and the functions for threads in GLib. I have a thread (from now on will be called thread A) that is created when I hit an "ok" button in a certain graphical window. Thread A starts doing some heavy tasks. Another button named "cancel" is available to stop and finish thread A at any moment.
My aim is to code a function for the thread created when I hit the "cancel" button (thread B) that has the ability to end the thread A.
I create thread A with the function g_thread_create
. However I cannot find any function similar to g_thread_cancel
to stop thread A using thread B. Is this possible or cannot be done?
Thank you so much for any kind of information provided.
You might want to consider using GTask
to run your task in a thread, rather than using a manually-created thread. If you use g_task_run_in_thread()
, the operation will run in a separate thread automatically.
GTask
is integrated with GCancellable
, so to cancel the operation you would call g_cancellable_cancel()
in the callback from your ‘Cancel’ button.
As OznOg says, you should treat the GCancellable
as a way of gently (and thread-safely) telling your task that it should cancel. Depending on how your long-running task is written, you could either check g_cancellable_is_cancelled()
once per loop iteration, or you could add the GSource
from g_cancellable_source_new()
to a poll loop in your task.
The advice about using threads with GLib is probably also relevant here.