如何在锁定端口的同时在线程之间切换?
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"
}
输出:(在超级终端中)
Hi 1
Hi 1
Hi 1
这里因为线程1被锁定并且处于无限循环中,所以它根本不是从线程1中出来的..但我需要线程1和线程2同时打印..请帮助我。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,如果他们使用相同的端口,他们就不能同时打印...但是你可能的意思是这样的:
这里我们只在写入期间获取锁- 所以在我们释放锁后,另一个线程有机会进入并获取锁。
但有两点:
SerialPort
中的其他哪些代码可能会锁定其监视器。Well they can't print simultaneously if they're using the same port... but you might mean this:
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:
SerialPort
may lock on its monitor.