help with a multithreaded design

G

Guest

I'm writing simulator to help with testing out problems with deadlocking on a
database.

I have a function which I call from a delegate BeginInvoke call, and
depending on the simulation I might have from three to 20 threads running.

here's the function...
void DoTest()
{
for(int jj=0;jj<Y;jj++)
{

for(int ii=0;ii<N;ii++)
{
Work1();
Work2();
}
CleanUp();
}

the threading question, that I can't get my head around, is how do I make
the call to CleanUp() mutually exclusive of everything else.
that is to say I want Work1() and Work2() to be executing in parallel, but
if any thread is running Work1() or Work2(), then CleanUp() can't run, and if
any thread is in CleanUp(), then Work1() and Work2() can't run.
However I don't want a solution which requires all the running threads to
complete the inner loop of work1() and work2().

Any ideas?
 
K

Ken Kolda

You could use the System.Threading.ReaderWriterLock class to achieve this.
During the calls to Work1() and Work2(), acquire a reader lock, and during
Cleanup(), acquire a writer lock. This will allow multiple calls to Work1()
and Work2() to execute concurrently but not at the same time as any call to
Cleanup().

Ken
 
M

morgal

You need to make a registry of threads that are running,
a scheuler, and have each thread check in before
executing and check out before it terminates.
 
W

William Stacey [MVP]

object readonly syncLock = new object();

for(int i=0; i< N;i++)
{
lock(syncLock)
{
Work1();
}
lock(syncLock)
{
Work2();
}
lock(syncLock)
{
CleanUp();
}
}

I think this would work if I understand you needs. If Cleaning up, any
Work() blocks. If no thread in CleanUp(), then threads run. The locks
probably belong inside the methods then wrapped around like this - but
either way.
 
J

Jon Skeet [C# MVP]

William Stacey said:
object readonly syncLock = new object();

for(int i=0; i< N;i++)
{
lock(syncLock)
{
Work1();
}
lock(syncLock)
{
Work2();
}
lock(syncLock)
{
CleanUp();
}
}

I think this would work if I understand you needs. If Cleaning up, any
Work() blocks. If no thread in CleanUp(), then threads run. The locks
probably belong inside the methods then wrapped around like this - but
either way.

No - that stops several threads from executing the Work blocks at the
same time. I think Ken is on the right track with ReaderWriterLock.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top