Thread synchronization design

80 views Asked by At

I have a class in my project which contains 4 vectors

m_vecA;
m_vecB;
m_vecC;
m_vecD;

These vectors can be accessed in different threads.I can use one critical section and protect all these vectors with it.

Or is it good idea to have 4 critical sections one for each resource? If I use one critical section for all resources I am seeing deadlock issue.

Generally is it good design to have one critical section for one resource or can we have one critical section per class?

3

There are 3 answers

1
Glenn Teitelbaum On BEST ANSWER

Have 4 critical sections, but:

The trick is to always access (lock) them in the same order,

say A then B then C then D

Otherwise you can deadlock if:

thread one locks A and is waiting for B,

and thread 2 locks B and is waiting on A

This cannot happen if you enforce a critical section ordering

1
Coder101101010 On

You should have one critical section for each item that needs to be accessed simultaneously.

Basically, a critical section for all four would mean that if one is locked by one thread, none of them can be read or written by other threads. A critical section for each would mean up to four threads could access them all at the same time.

0
wjl On

If you have 4 separate, independent resources, and it doesn't matter what they contain in relationship to each other, you probably want to protect them separately and independently.

However, if those 4 vectors, together, represent a single logical resource, and they must always be updated atomically and stay valid with respect to each other, you'll want to protect them as a group.

Or is it good idea to have 4 critical sections one for each resource? If I use one critical section for all resources I am seeing deadlock issue.

As was mentioned in other answers, this will happen if you threads are locking more than one resource at a time and are not always locking them in the same order.

Keep in mind that if threads always need to lock all four vectors to work with them, you don't want to protect them individually, but as a single group.

Generally is it good design to have one critical section for one resource or can we have one critical section per class?

This again depends on whether each vector represents a completely independent resource, or whether all 4 vectors, as a group, are a single logical resource. The fact that you have put them in a class together seems to indicate the latter. If this is true, you should thus have a single lock protecting all of them as a group.