Hello NG,
is there a good, easy and safe way to:
- put all threads into a 'wait until I tell you to continue'
- get feed back that all threads are now waiting
< I now want to do some major data update >
- tell all threads to continue with work
Sure. Do it the same way anyone else would:
* create an object instance for use with the lock() statement
* protect code that shares data with other threads with the
lock() statement, including the thread that will do the
"major data update"
In the simplest case, you'd simply enter the lock() statement at regular
intervals during the processing. Eventually the main update thread would
be granted ownership of the lock, at which time it could be assured that
all of the other threads have reached a convenient stopping point and are
waiting for the update to finish.
Assuming the working threads don't conflict with each other, you would
probably want to have a different locking object for each thread. Then
you can use Monitor.TryEnter() from the main update thread to try to
acquire each of the working threads' locks; once it's finally gotten all
of the locks, it can safely perform whatever update you need it to.
You aren't very specific about your design, but if you can design things
so that the main update performs whatever update it needs to independently
from the working threads, and then can individually apply those updates to
each thread, that would avoid having all of the worker threads all waiting
at the same time. Given the assumption that the worker threads don't need
synchronization between each other, only with the main update thread,
there should be no problem implementing a solution this way.
If you need to put some larger block of code, one that won't exit the
lock() statement in any sort of timely fashion, into the lock() statement
but still want the working threads to be responsive in their sharing of
the lock, there are other more complicated techniques you can use. The
Monitor class, for example, provides different methods that allow a lock
to be released and acquired intermittently, as well as providing for a
"wait queue" where threads can be placed until some other thread signals
that there's no need to wait anymore.
As in the more basic solution, depending on how the threads depend on each
other, you could either assign a specific locking object to each thread,
or have the threads cooperate with each other as well as the main updating
thread. In some cases, it may be useful to have a volatile flag or some
kind of synchronization object for use for signaling between the threads.
Without knowing more about the problem, it's hard to say.
But it would be simplest if you could simply protect a small section of
code with the lock() statement, one that the working thread doesn't stay
executing inside for any single long length of time. And simpler is
usually better for multithreaded code.
Pete