pthread implementation of a ticket lock

This commit is contained in:
Nils O. Selåsdal
2014-06-25 16:48:42 +02:00
parent d28288f048
commit 06be01a708
2 changed files with 92 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
#ifndef UC_TICKET_LOCK_H_
#define UC_TICKET_LOCK_H_
#include <pthread.h>
/** An fair alternative to a bare pthread_mutex_t to prevent starvation*/
struct UCTicketLock {
pthread_cond_t cond;
pthread_mutex_t mutex;
unsigned long queue_head, queue_tail;
};
/** Static initializer for an UCTicketLock. Use as e.g
*
* struct UCTicketLock my_lock = UC_TICKET_LOCK_INITIALIZER;
*/
#define UC_TICKET_LOCK_INITIALIZER { PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,0, 0}
/** Initialize a UCTicketLock.
* The default attributes for the pthread mutex and condition variable is used.
*
* @return 0 on success, errno value on failure
*/
int uc_ticket_lock_init(struct UCTicketLock *lock);
/** Initialize a UCTicketLock with attributes
*
* @param mattr attribute used for the mutex, or NULL
* @param cattr attribute used for the condition variable, or NULL
*
* @return 0 on success, errno value on failure
*/
int uc_ticket_lock_init_ex(struct UCTicketLock *lock, pthread_mutexattr_t *mattr, pthread_condattr_t *cattr);
/** Acquire the lock
*/
void uc_ticket_lock(struct UCTicketLock *lock);
/** Release the lock
*/
void uc_ticket_unlock(struct UCTicketLock *lock);
#endif