开发者

how to switch between threads while locking a port?

开发者 https://www.devze.com 2023-01-09 03:17 出处:网络
static SerialPort port = new SerialPort(\"COM3\", 57600, Parity.None, 8, StopBits.One); thread1() { lock(port)
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 co开发者_StackOverflowming out of thread1 at all.. but i need thread1 and thread2 to print simultaneously.. Please help me out.

Thanks.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号