如何使用互斥锁
我有一个线程,正在发送存储在 List< 类型的缓冲区中的数据。字符串>通过 TCP。另一个线程正在写入缓冲区。由于我对 c# 不太熟悉,我想知道应该如何正确使用锁或互斥锁。
这是我最终想要使用的代码:
while(buffer.isLocked())
{
buffer.wait();
}
buffer.lockBuffer();
buffer.add(tcpPacket);
buffer.unlockBuffer();
buffer.notify();
这是我当前的代码。我希望有人能帮助我完成它。
public class Buffer
{
private Mutex mutex;
private List<string> buffer;
private bool locked = false;
public Buffer()
{
mutex = new Mutex(false);
buffer = new List<string>();
}
public bool isLocked()
{
return locked;
}
public void lockBuffer()
{
if (!locked)
{
//...
locked = true;
}
}
public void unlockBuffer()
{
if(locked)
{
mutex.ReleaseMutex();
locked = false;
}
}
public void wait()
{
mutex.WaitOne();
}
public void notify()
{
//...
}
}
I have one thread, that is sending data stored in a buffer of type List< string> via tcp. Another thread is writing into the buffer. As I am not very familiar with c# I'd like to know how I should use lock or Mutex correctly.
This is the code I'd like to use eventually:
while(buffer.isLocked())
{
buffer.wait();
}
buffer.lockBuffer();
buffer.add(tcpPacket);
buffer.unlockBuffer();
buffer.notify();
This is my current code. I hope someone can help me complete it.
public class Buffer
{
private Mutex mutex;
private List<string> buffer;
private bool locked = false;
public Buffer()
{
mutex = new Mutex(false);
buffer = new List<string>();
}
public bool isLocked()
{
return locked;
}
public void lockBuffer()
{
if (!locked)
{
//...
locked = true;
}
}
public void unlockBuffer()
{
if(locked)
{
mutex.ReleaseMutex();
locked = false;
}
}
public void wait()
{
mutex.WaitOne();
}
public void notify()
{
//...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 System.Collections.Concurrent.BlockingCollection 会更好。它不需要外部同步。
对于那些不使用4.0的人
It would be better if you use
System.Collections.Concurrent.BlockingCollection
. It doesn't require an external sync.For those who don't use 4.0
以下代码不是线程安全的。如果两个线程同时进入此方法,则两个线程都可能成功通过 if 条件。
您可能只是想做这样的事情:
我不认为您正在做一些复杂的事情,需要的不仅仅是简单易用的锁定语句。
The following code is not thread-safe. If two threads are entering this method at the same time, both might pass the if condition successfully.
You simply might want to do something like this:
I don't think you're doing something sophisticated that requires more than the simple to use lock-statement.
我不会使用互斥体,因为我想您不处理多进程同步。锁非常好并且更容易实现:
用法很明显(按照您的要求):
I wouldn't use Mutexes since I suppose you aren't dealing with multiple processes synchronization. Locks are pretty fine and simpler to implement:
The usage is obviously (as you requested):