next up previous contents index
Next: Miscellaneous Up: The Foreign Include File Previous: Prolog exceptions in foreign   Contents   Index

Foreign code and Prolog threads

If SWI-Prolog has been build to support multi-threading (see threads), all foreign-code linked to Prolog should be thread-safe (reentrant) or guarded in Prolog using with_mutex2 from simultaneous access from multiple Prolog threads. On Unix systems, this generally implies the code should be compiled with the -D_REENTRANT flag passed to the compiler. Please note that on many Unix systems not all systemcalls and library-functions are thread-safe. Consult your manual for details.

If you are using SWI-Prolog as an embedded engine in a multi-threaded application you can access the Prolog engine from multiple threads by creating an engine in each thread from which you call Prolog. Without creating an engine, a thread can only use functions that do not use the term_t type (for example PL_new_atom).

Please note that the interface below will only work if threading in your application is based on the same thread-library as used to compile SWI-Prolog.

intPL_thread_self Returns the integer Prolog identifier of the engine or -1 if the calling thread has no Prolog engine. This function is also provided in the single-threaded version of SWI-Prolog, where it returns -2. intPL_thread_attach_enginePL_thread_attr_t *attr Creates a new Prolog engine in the calling thread. If the calling thread already has an engine the reference count of the engine is incremented. The attr argument can be NULL to create a thread with default attributes. Otherwise it is a pointer to a structure with the definition below. For any field with value `0', the default is used.


\begin{code}
typedef struct
{ unsigned long local_size; /* Stack sizes (K-bytes)...
...ng argument_size;
char * alias; /* alias name */
} PL_thread_attr_t;
\end{code}

The structure may be destroyed after PL_thread_attach_engine has returned. If an error occurs, -1 is returned. If this Prolog is not compiled for multi-threading, -2 is returned. intPL_thread_destroy_engine Destroy the Prolog engine in the calling thread. Only takes effect if PL_thread_destroy_engine is called as many times as PL_thread_attach_engine in this thread. Returns TRUE on success and FALSE if the calling thread has no engine or this Prolog does not support threads.

Please note that construction and destruction of engines are relatively expensive operations. Only destroy an engine if performance is not critical and memory is a critical resource. The engine is automatically destroyed if the thread finishes, regardless how many times PL_thread_attach_engine has been called.


next up previous contents index
Next: Miscellaneous Up: The Foreign Include File Previous: Prolog exceptions in foreign   Contents   Index
Dr. Richard Botting 2001-12-12