tags:

views:

38

answers:

1
static SerialPort port = new SerialPort("COM3", 57600, Parity.None, 8, StopBits.One);
thread1()
{

   lock(port)
   for(;;)
      port.write"Hi 1";
}
thread2()
{
   lock(port)
   for(;;)
      port.write"Hi 2"
}

output:(in Hyper-Terminal)

Hi 1
Hi 1
Hi 1

here as thread1 is locked and is in a infinite loop, so its not coming out of thread1 at all.. but i need thread1 and thread2 to print simultaneously.. Please help me out.

Thanks.

+2  A: 

Well they can't print simultaneously if they're using the same port... but you might mean this:

void Thread1()
{    
   for(;;)
   {
      lock (port)
      {
          port.Write("Hi 1");
      }
   }
}

void Thread2()
{    
   for(;;)
   {
      lock (port)
      {
          port.Write("Hi 2");
      }
   }
}

Here we only acquire the lock for the duration of the write - so there's a chance for another thread to come in and acquire the lock after we've released it.

Two points though:

  • I wouldn't like to guarantee what will happen here. I wouldn't be surprised to see one thread still write for quite a long time, as it may get to reacquire the lock before the other thread gets a timeslice. It will depend on the scheduler and how many cores you have.
  • Generally speaking I prefer to lock on a monitor created solely for the purposes of locking. You don't know what other code inside SerialPort may lock on its monitor.
Jon Skeet
@Jon Skeet: Thanks for your reply. I worked on it and as you said, It waits on a thread for a long time. Im fact I have 12 threads and its stuck wt thread 1 and 2 itself.. You have also mentioned about monitor, can u please throw some more light on it. Thanks.
SLp
@user403489: The lock statement works on a monitor - effectively there's a monitor associated with each object in .NET (although they're lazily allocated).
Jon Skeet