question
What parallel pattern fits best around an AutoResetEvent?
background
When comparing options for synchronization between threads we might compare AutoResetEvent to ManualResetEvent. Consider these two distinctions:
- AutoResetEvent releases at most one waiting thread.
- AutoResetEvent resets automatically after one waiting thread is released.
It is important to note that if two threads are waiting and an AutoResetEvent fires twice, it is possible for a race condition to occur and only one thread is released. More locks could be used to protect from this condition – but the focus of the question is about what pattern AutoResetEvent does best (and perhaps this implies, what pattern it supports best on its own).
I’m not sure we can talk about parallel patterns in this case. Patterns are on a much higher level of abstraction than mere synchronization mechanisms such as
AutoResetEvent.When we speak of parallel patterns we refer to generic methods of solving common parallelism problems like geometric decomposition of a data structure, parallel divide-and-conquer, producer-consumer and so on, which can be concretely implemented with a whole range of lower-level mechanisms and are language and platform agnostic.
AutoResetEventis a .NET synchronization mechanism. It can be used together with theThreadclass to implement one of the above patterns in a concrete case, but then this implementation can very well be substituted with pthreads and condition variables for example.The way I was taught to view things when solving a parallelism problem was along these three steps, from abstract to concrete:
Edit: Ok, after looking around my old “stuff” I’ve identified a pattern that can have an implementation using
AutoResetEvent. For a good explanation of the problem check out my old question here: Parallel application has random behaviorAs you can see from the description, before starting to compute a row allocated to it, each thread must wait for a companion thread to process at least the first few items of the previous row. That means that each thread has to block at the beginning of each row assigned to it and wait for a signal. So assuming we have 3 threads processing the matrix, thread 0 would block at the beginning of rows 0, 3, 6… thread 1 at rows 1, 4, 7… and so on.
This wait-to-be-signaled behavior can be easily implemented using an
AutoResetEventper thread because each thread needs to block several times, meaning that we need to reset the event several times and there is no danger of it being signaled quickly in a sequence because the threads have to wait for each other to advance.