SWI-Prolog 5.6.53 Reference Manual: Section 8.8

## 8.8 Multithreading and the XPCE graphics system

GUI applications written in XPCE can benefit from the multi-threaded version of XPCE/SWI-Prolog if they need to do expensive computations that block to UI in the single-threaded version.

Due to various technical problems on both Windows and Unix/X11 threading is best exploited by handing long computations to their own thread.

The XPCE message passing system is guarded with a single mutex, which synchronises both access from Prolog and activation through the GUI. In MS-Windows, GUI events are processed by the thread that created the window in which the event occurred, whereas in Unix/X11 they are processed by the thread that dispatches messages.

Some tentative work is underway to improve the integration between XPCE and multi-threaded SWI-Prolog. There are two sets of support predicates. The first model assumes that XPCE is running in the main thread and background threads are used for computation. In the second model, XPCE event dispatching runs in the background, while the foreground thread is used for Prolog.

XPCE in the foreground Using XPCE in the foreground simplifies debugging of the UI and generally provides the most comfortable development environment. The GUI creates new threads using thread_create/3 and, after work in the thread is completed, the sub-thread signals the main thread of the completion using in_pce_thread/1.

in_pce_thread(:Goal)
  Assuming XPCE is running in the foreground thread, this call gives background threads the opportunity to make calls to the XPCE thread. A call to in_pce_thread/1 succeeds immediately, copying Goal to the XPCE thread. Goal is added to the XPCE event-queue and executed synchronous to normal user events like typing and clicking.

XPCE in the background In this model a thread for running XPCE is created using pce_dispatch/1 and actions are sent to this thread using pce_call/1.

pce_dispatch(+Options)
  Create a Prolog thread with the alias-name `pce` for XPCE event-handling. In the X11 version this call creates a thread that executes the X11 event-dispatch loop. In MS-Windows it creates a thread that executes a windows event-dispatch loop. The XPCE event-handling thread has the alias `pce`. Options specifies the thread-attributes as thread_create/3.
pce_call(:Goal)
  Post Goal to the `pce` thread, executing it synchronous with the thread's event-loop. The pce_call/1 predicate returns immediately without waiting. Note that Goal is copied to the `pce` thread.

For further information about XPCE in threaded applications, please visit http://gollem.science.uva.nl/twiki/pl/bin/view/Development/MultiThreadsXPCE