jsp
jsp

Reputation: 143

Thread synchronization based on value

I'm trying to synchronize threads in a critical section, but I need to do it based on a value. For example if you have threads doing work representing different people (ie bob, fred, bill) then the threads for Bob and Bill could be concurrent, but all of Bob's threads would be synchronized so that only 1 can go through the critical section at a time. My initial thoughts are to use named mutex, but not sure how to manage them. Perhaps some type of dictionary of named mutexes. Has anyone done something similar?

Upvotes: 2

Views: 162

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

  • If you have a Person class representing the person (Bob, Bill, etc.), you can lock on that instance.
  • If you do not have a class representing a Person, create a Dictionary that maps unique identifiers of your people to instances of named Mutex objects. The access to the dictionary itself should be synchronized. Also note that mutex creation in .NET is non-trivial. See this answer for details.

Upvotes: 1

SLaks
SLaks

Reputation: 887797

Typically, in such scenarios, you will have a single User instance for each user.

If so, you can just lock() on that user instance.

Upvotes: 4

Related Questions