Pthread Qns on Mutex

i have a question regarding pthreads.
If i have the following code:
1
2
3
pthread_mutex_lock(&mutexT1)
DO_Something_A
pthread_mutex_unlock(&mutexT1);


Over here, I have a list of TaskA to do and i wish to have lock my mutexT1 when working on TaskA. The question is if i am given another mutex called mutexT2 which can help to do TaskA by using another thread, how should i specify this in my function code.

Objective: I wish to have two threads doing TaskA.
i want a similar behaviour as the following but I do not know how to achieve.
1
2
3
Either mutexT1 or mutexT2 available, lock one of them
Do something A
unlock it


Please advice. Thanks
Exactly why do you have two mutexes?
Do you want to make sure that no more than two threads can perform that task at the same time?
Actually there are more than 2 threads in my program. They are sharing 2 resources to speed up their work in completing the task A.
If i have 1 resource, i would use pthread_mutex_lock so that only 1 resource is taken by a thread per time, which means not more than 1 thread can do taskA at 1 time.

But if i have 2 resources, how can i achieve that any 2 threads can do taskA at a time while the rest must wait for either 1 of the 2 resources is freed up?


Last edited on
Suppose you have this code:
1
2
3
4
5
mutex1.lock();
//...
access_shared_resource1();
//...
mutex1.unlock();
and you want to change it into this:
1
2
3
4
5
6
7
mutex1.lock();
//...
access_shared_resource1();
//...
access_shared_resource2();
//...
mutex1.unlock();
while allowing more than one thread to run the non-serial parts.

Some possible solutions are:
Synchronize more finely:
1
2
3
4
5
6
7
8
9
//...
mutex1.lock();
access_shared_resource1();
mutex1.unlock();
//...
mutex2.lock();
access_shared_resource2();
mutex2.unlock();
//... 

Stick resource accesses together:
1
2
3
4
5
6
7
//...
mutex1.lock();
access_shared_resource1();
access_shared_resource2();
mutex1.unlock();
//...
//... 

Be careful when synchronizing too finely.
hi thanks for ur reply. in fact, my '2 resources' are indented to be a lock while the actual shared variable is in TaskA.
I guess my solution is to u a count semaphores instead of mutex ;)
Last edited on
Topic archived. No new replies allowed.