GVillani82
GVillani82

Reputation: 17429

Dealing with thread in C# (deadlock)

I'm using thread in C# application. I have the following scenario:

The thread A, calls thread B, using this code:

ThreadStart t = () => StreamManager.ManageStream.mixThread(ref streamClosed, ref opEnded);
Thread threadB = new Thread(t);
threadB.Start();

The thread B do this work repeatedly:

while (!streamClosed)
    {
         System.Threading.Thread.Sleep(3000);
         //some stuff here
    }
opEnded = true;

the boolean streamClosed and opEnded are passed from thread A to thread B, by reference (using ref keyword)

The thread A, after starting the thread B, do the following:

streamClosed = true;
while(!opEnded)
{
    System.Threading.Thread.Sleep(1000); //wait 
}

and the thread B stop its work. But in some situation, seems to be in deadlock, remains blocked since I kill it from the Activity Manager in Windows.

What is wrong?

Upvotes: 2

Views: 169

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273264

define opEnded as volatile .

It is probably being cached (by the compiler/optimizer).


But that is a quick and minimal fix for code that is wrong at a deeper level.

Real code shouldn't Sleep(). There are much better ways to makes threads sync with each other. Which one to use depends very much on what you actually want to do. You shouldn't actually use volatile.

Upvotes: 5

Related Questions