4 Locks and Threads
When writing multithreaded programming, it is not always safe to access the same data in multiple threads at the same time.
Libevent structures typically have three ways of working with multithreading:
² Some structures are inherently single-threaded: it is always unsafe to use them in multiple threads at the same time.
² Some structures have optional locks: You can tell libevent whether each object needs to be used in multiple threads.
² The total number of structures is locked: If Libevent is running under a configuration that supports locks, it is always safe to use them in multiple threads.
To acquire a lock, you must tell Libevent which lock function to use before calling the Libevent function that allocates a struct that needs to be shared between multiple threads.
If you use the Pthreads library, or if you use the Windows native thread code, you are fortunate that there are already set up libevent predefined functions that can correctly use Pthreads or Windows functions. Interface [CPP] view plain copy #ifdef WIN32 int evthread_use_windows_threads (void); #define EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED #endif #ifdef _event_have_pthreads int evthread_use_pthreads (void); #define Evthread_use_pthreads_implemented #endif
These functions return 0 when they succeed, and 1 when they fail.
If you use a different line threading, you need some extra work, you must use your line threading to define the function to achieve:
L Lock
L Lock
L Unlock
L Assign Locks
L-destructor Lock
L Condition Variable
L Create a condition variable
L destructor Condition variable
L Wait for condition variable
L Trigger/broadcast a condition variable
L Thread
L Thread ID detection
Use the Evthread_set_lock_callbacks and Evthread_set_id_callback interfaces to tell libevent these functions. Interface
[CPP] View plain copy #define EVTHREAD_WRITE 0x04 #define EVTHREAD_READ 0x08 #define EVTHREAD_TRY 0x10 # define evthread_locktype_recursive 1 #define evthread_locktype_readwrite 2 #define EVTHREAD_LOCK_API_VERSION 1 struct evthread_lock_callbacks { int lock_api_version; unsigned supported_locktypes; void * (*alloc) (unsigned locktype); void (*free) (Void *lock, unsigned locktype); int (*lock) (Unsigned mode, void *lock); int (*unlock) (unsigned mode, void *lock); }; int evthread_set_lock_callbacks (const struct evthread_lock_callbacks *); Void evthread_set_id_callback (unsigned long (*ID_FN) (void); struct evthread_condition_callbacks { int condition_api_version; void * (*alloc_condition) (Unsigned condtype);