c++multithreadinglockingmutexstdmutex

C++ Mutex locking for a set of threads


I understand the basic principle of mutex's is to protect specific code path from being accessed by more than 1 threads.

In my current setup, I have 10 threads of type A (A1-A10), and 10 threads of type B(B1-B10). By type I mean, threads that are running infinite loop and calling method A() and B() respectively. From these methods A and B, they are both calling a function X().

What I'm trying to do is, lock a certain part of code in function X(), so that at any time from a pair of A and B (A1:B1, A2:B2...) only 1 is accessing that path. Meaning either A1 is in that code path or B1, similarly either A2 is in that code path of B2 and so on. Its fine if A1,A2,B3,B4,A5.. are accessing that code path at the same time. It's just that from a A-B pair there is only 1 thread accessing this code.

How do I implement that?

X() {

// 
Lock this code so that either of (A1, B1) can access it 
and so on..
//
}


Solution

  • What you're looking for is 10 mutexes, one for A1/B1, one for A2/B2, etc. You can put them in an array and just access the proper one.

    Also, to be clear, mutexes don't usually protect code paths. What they protect is data. So if you have a list, that list might have a mutex so that only one thread at a time can be modifying the list (and no thread accesses a list while another thread is modifying it). If you have multiple lists, you give each list its own mutex, so the same code path will be in use by multiple threads at once, but it's OK because each is working with a different list. It sounds from your description that something like this is what you're trying to do.