c - is it reasonable/sensible to create many thread condition variables and mutexes? -
i have program 1+n threads, , n fifo queues, like: fifo_queue_t* fifo_queque[n]. 1 thread responsible filling these n fifo queues. , each of other threads related 1 fifo queue.
for each of other thread , keeps on checking whether fifo queue fifo_queue[i], if not empty, fetch elements fifo_queue , make fifo_queue empty again.
now problem how checking(or polling if prefer). 1 way is
for(;;) { if(fifo_queue[i] != null) { fetch_all_element(); } }
in way, may cpu-consuming? alternative approach use pthread_cond_t variable,
for(;;){ pthread_mutex_lock(&mut); if(fifo_queue[i] == null) { pthread_cond_wait(&cond, &mut); fetch_all_element(); } pthread_mutex_unlock(&mut); }
but in way, need create n condition variables , mutexes, n threads. resource-consuming? there ways blocking thread on condition until satisfied? thanks!
i working on project sounds similar doing. link
what did create thread safe queue block process trying dequeue queue if empty or block process trying enqueue if queue full. once entry added queue, consuming process signaled. way not wasting cpu cycles polling each thread.
not sure works in scenario, might give idea how solve problem.
edit : here additional function might of use. returns '1' queue empty. similar function isfull() created off of this.
int isempty(queue *q) { int ret; sem_wait(q->excl); if (q->count <= 0) ret = 1; else ret = 0; sem_post(q->excl); return ret; }
Comments
Post a Comment