I have several threads that use the use of semaphore. Thread A holds the semaphore (using locks), and threads B and C wait for the same semaphore (also using locks). Streams are shared by global variables, etc.
Is there a way in C # that I can use to close thread B? I can set the flag to and have thread B check this flag and exit as soon as it takes control of the semaphore, but I donβt know any technique for thread A to give semaphore to thread B (and get it back when thread B ends ), without risking to control the capture of thread C.
Anyone have any suggestions to solve this design problem? I can rewrite the program as necessary if I approach it incorrectly.
[Edit] One commenter indicated that I am using the wrong terminology. The comment is correct: I use a critical section, but given that everything works in one process, in this example the critical sections are functionally equivalent to the more general term "semaphore".
[Edit] Someone asked for details, so here it is.
There are several threads executing code A. There is only one thread executing code B.
Code A:
private static Thread workerThread = null;
lock (lockObject)
{
... do some work ...
if (...condition...)
{
if (workerThread != null)
{
quitWorkerThread = true;
while (workerThread.IsAlive)
{
Thread.Sleep(50);
}
workerThread = null;
quitWorkerThread = false;
}
}
... do some more work ...
if (...condition...)
{
if (workerThread == null)
{
workerThread = new Thread(WorkerThread);
workerThread.Start();
}
}
... do even more work ...
}
Code B:
private void WorkerThread()
{
while (true)
{
if (quitWorkerThread)
{
return;
}
Thread.Sleep (2000);
if (quitWorkerThread)
{
return;
}
lock(lockObject)
{
if (quitWorkerThread)
{
return;
}
... do some work ...
}
}
}
I suspect that the Aaron solution option will be what I use. I mostly hoped that there was a slightly more elegant solution, but I suspect that, like everything else in this project, all these are brute forces and corner cases: - (.
source
share