【发布时间】:2013-11-19 06:24:23
【问题描述】:
我有 2 个线程要同时触发并并行运行。这两个线程将处理一个字符串值,但我想确保没有数据不一致。为此,我想使用带有Monitor.Pulse 和Monitor.Wait 的锁。我使用了在另一个问题/答案中找到的方法,但是每当我运行程序时,第一个线程都会卡在Monitor.Wait 级别。我认为那是因为第二个线程已经“脉冲”和“等待”。下面是一些代码:
string currentInstruction;
public void nextInstruction()
{
Action actions = {
fetch,
decode
}
Parallel.Invoke(actions);
_pc++;
}
public void fetch()
{
lock(irLock)
{
currentInstruction = "blah";
GiveTurnTo(2);
WaitTurn(1);
}
decodeEvent.WaitOne();
}
public void decode()
{
decodeEvent.Set();
lock(irLock)
{
WaitTurn(2);
currentInstruction = "decoding..."
GiveTurnTo(1);
}
}
// Below are the methods I talked about before.
// Wait for turn to use lock object
public static void WaitTurn(int threadNum, object _lock)
{
// While( not this threads turn )
while (threadInControl != threadNum)
{
// "Let go" of lock on SyncRoot and wait utill
// someone finishes their turn with it
Monitor.Wait(_lock);
}
}
// Pass turn over to other thread
public static void GiveTurnTo(int nextThreadNum, object _lock)
{
threadInControl = nextThreadNum;
// Notify waiting threads that it's someone else's turn
Monitor.Pulse(_lock);
}
知道如何让 2 个并行线程在同一个周期内使用锁或其他任何东西进行通信(操作相同的资源)吗?
【问题讨论】:
-
您并行调用 fetch 和 decode,但同时锁定它们,因此在任何给定时间只有一个可以执行。您应该考虑一下您的程序,一定有更好的方法。
标签: c# multithreading locking