c - Producer consumer multiple mutex needed to access critical section? -


there 3 tools. consumer needs 2 tools modify buffer. if consumer takes 2 tools , consumer b takes 1, consumer b have wait tool released.

i not sure if i'm thinking problem in right way. way interpret need 3 mutex , consumer has lock 2 out 3, right idea?

i don't think should using semaphores because don't want multiple threads accessing shared resource @ same time. in normal producer consumer problem there 1 mutex lock here need 2 of 3 how approach this?

yes, can use 3 mutexes, must careful avoid deadlock. so, must establish known order acquire locks: example, acquire lock tool lowest identifier first. in situations these, avoiding deadlock matter of acquiring locks in same order.

some pseudo-code:

pthread_mutex_t locks[3]; // 1 lock each tool  critical_function() {     /* acquire 2 tools, t1 , t2 */     first = min(t1, t2);     second = max(t1, t2);     locks[first].lock();     locks[second].lock();     /* work... */     locks[first].unlock();     locks[second].unlock(); } 

this assumes associate id each tool in range 0-2.

but notice, if will, no more 1 producer / consumer can working @ same time, since there 3 tools only. might want use single mutex instead, lock it, acquire 2 tools, work , release - after all, there not possibility parallelism, have @ 1 producer / consumer working, , others waiting while holding 1 tool.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -