Re: Thread safe queue in C
- From: "Chris Thomasson" <cristom@xxxxxxxxxxx>
- Date: Fri, 22 Feb 2008 16:51:12 -0800
"Behzad" <Sedighzadeh@xxxxxxxxx> wrote in message news:dbb12be7-2214-4e38-bbdf-d4a0978d530c@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hi all,
I am in the middle of developing a multithreaded embedded program
within linux with C and i need a thread safe queue.How can i obtain a
library to do my job? my time is short so developing a library from
scratch is considered a very bad idea.
please conduct me to do that.
Your on Linux, so why not use PThreads? Are you looking for extreme peformance, perhaps real-time? How many producers and consumers will be hitting the queue at any one time? Anyway, creating a queue with POSIX Threads is rather trivial, I don't see why you can't quickly create one:
extremely quick brief pseudo-code
______________________________________________________
typedef struct node_s node;
typedef struct queue_s queue;
struct node_s {
node* next;
void* state;
};
struct queue_s {
node* head; /* = 0 */
node* tail; /* = 0 */
pthread_mutex_t mtx;
pthread_cond_t cond;
};
void queue_push(
queue* const _this,
node* const n,
void* const state
) {
node* tail;
n->next = 0;
n->state = state;
pthread_mutex_lock(&_this->mtx);
if (! (tail = _this->tail)) {
_this->head = n;
} else {
tail->next = n;
}
_this->tail = n;
pthread_mutex_unlock(&_this->mtx);
pthread_mutex_signal(&_this->cond);
}
node* queue_pop(
queue* const _this
) {
node* head;
pthread_mutex_lock(&_this->mtx);
while (! (head = _this->head)) {
pthread_cond_wait(&_this->cond, &_this->mtx);
}
if (! (_this->head = head->next)) {
_this->tail = 0;
}
pthread_mutex_unlock(&_this->mtx);
return head;
}
______________________________________________________
.
- References:
- Thread safe queue in C
- From: Behzad
- Thread safe queue in C
- Prev by Date: Re: Thread safe queue in C
- Next by Date: Re: Do I ever need to do a sched_yield() for pthread_cond_signal(..) to work?
- Previous by thread: Re: Thread safe queue in C
- Next by thread: calloc interposing issue with -lpthread -ldl linked in
- Index(es):
Relevant Pages
|