This is only a quick overview of the Thread library. The reference of this library should give all its content.
The class of the thread object you want to create should inherit the THREAD class.
Your thread is represented by a class which inherits from THREAD (deferred
class).
class MY_THREAD inherit THREAD> ... feature execute is -- define the deferred feature from THREAD. do ... end ... end --class MY_THREADCreating a thread is like creating an Eiffel object:
my_thread: MY_THREAD -- MY_THREAD inherits from THREAD and defines -- the deferred procedure `execute' create my_thread
Note: You have created a thread object but have not started the thread itself yet.
To run the thread, use the feature launch from THREAD.
my_thread.launchOn the Eiffel side, the procedure execute will be launched. This procedure is deferred in class THREAD, you have to define it in MY_THREAD.
On the C side, a C thread will be created and launched.
Caution: you may call join_all and the end of the exceution of the parent thread if you do not want it to die before its child, otherwise they may prematurily terminate.
The implementation of the class MUTEX is mapped on the C standard thread library. An instance of class MUTEX can be shared between different thread.
my_mutex.pointer is the pointer to the nested C mutex of my_mutex.
my_mutex: MUTEX
create my_mutex.make
my_mutex.lock
my_mutex.unlock
my_mutex.try_lock
my_mutex.is_set
Note: on Windows: The MUTEX objects on Windows are recursive while they are not on Unix. A recursive mutex can be locked twice by the same thread.
Caution: be sure that a mutex is unlocked when it is disposed.
Like MUTEX, the features of this class are mapped on the C thread library. An instance of class SEMAPHORE can be shared between thread.
my_sem: SEMAPHORECreation of semaphore: initialize semaphore with nb_tokens, it requires nb_tokens >= 0
create my_sem.make (nb_tokens)
my_sem.wait
my_sem.post
my_sem.try_wait
Caution: be sure that a semaphore does not wait for a token when it is disposed
This class allows to use condition variables in Eiffel. An instance of class
CONDITION_VARIABLE can be shared between threads.
my_cond: CONDITION_VARIABLE
create my_cond.make
my_mutex: MUTEX create my_mutex.make
my_mutex must be locked by the calling thread so as wait can be called. wait atomically unlocks my_mutex and waits for the condition variable my_mutex to receive a signal. As soon as it received a signal, my_cond locks my_mutex;
my_mutex.lock -- You must lock `my_mutex' before calling wait. my_cond.wait (my_mutex) -- Here the critical code to execute when `my_cond' received a signal. my_mutex.unlock -- Unlock the mutex at the end of the critical section.
my_cond.signal
my_cond.broadcast
Caution: be sure that a condition variable is unblocked when it is disposed.
class THREAD_ATTRIBUTES: defines the
attributes of an Eiffel Thread regarding the thread scheduling policy and
priority.
thr: MY_THREAD ... thr.launch ... thr.join