C# 并行线程的资源访问
我有两个线程同时被触发并并行运行。这两个线程将处理一个字符串值,但我想确保没有数据不一致。为此,我想使用带有C# 并行线程的资源访问,c#,multithreading,locking,C#,Multithreading,Locking,我有两个线程同时被触发并并行运行。这两个线程将处理一个字符串值,但我想确保没有数据不一致。为此,我想使用带有Monitor.Pulse和Monitor.Wait的锁。我使用了在另一个问题/答案中找到的方法,但每当我运行程序时,第一个线程都会卡在监视器.Wait级别。我想那是因为第二个线程已经“脉冲”和“等待”。下面是一些代码: string currentInstruction; public void nextInstruction() { Action actions = {
Monitor.Pulse
和Monitor.Wait
的锁。我使用了在另一个问题/答案中找到的方法,但每当我运行程序时,第一个线程都会卡在监视器.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);
}
你知道如何让两个并行线程在同一个周期内使用锁或其他工具进行通信(操作相同的资源)吗?你想并行运行两段代码,但在开始时使用相同的变量锁定它们 正如nvoigt提到的,这听起来已经错了。您需要做的是从那里移除
锁
。仅当您要以独占方式访问某些内容时才使用它
顺便说一句,“数据不一致”可以通过不需要它们来避免。不要直接使用currentInstruction
字段(它是字段吗?),而是提供线程安全的currentInstruction
属性
private object _currentInstructionLock = new object();
private string _currentInstruction
public string CurrentInstruction
{
get { return _currentInstruction; }
set
{
lock(_currentInstructionLock)
_currentInstruction = value;
}
}
另一件事是命名,从
开始的局部变量名称是一种糟糕的样式。一些人(包括我)使用它们来区分私有字段。属性名应该从BigLetter开始,局部变量从small开始。您可以并行调用fetch和decode,但要锁定它们,以便在任何给定时间只能执行一个。你应该考虑一下你的计划,一定有更好的办法。谢谢。根据我对锁的理解,我很快就把它拼凑起来了,但当它不起作用时,我就不知所措了。我在每个方法中都使用等待句柄。你认为我可以利用这些来实现我的目标吗?我将编辑我的问题以反映我的意思。