首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过并行线程访问资源

问通过并行线程访问资源
EN

Stack Overflow用户
提问于 2013-11-19 14:24:24
回答 1查看 336关注 0票数 0

我有两个线程触发在同一时间和并行运行。这两个线程将操作字符串值,但我希望确保没有数据不一致。为此,我想使用带有Monitor.Pulse和Monitor.Wait的锁。我使用了在另一个问题/答案上找到的方法,但是每当我运行我的程序时,第一线程卡在Monitor.Wait级别。我想这是因为第二个线程已经"Pulsed“和"Waited”了。下面是一些需要查看的代码:

代码语言:javascript
复制
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);
}

你知道如何让两个并行线程在同一个周期内使用锁或其他东西进行通信(操作相同的资源)吗?

EN

回答 1

Stack Overflow用户

发布于 2013-11-19 15:01:03

你想并行运行两段代码,但是在开始时使用相同的变量锁定它们?

正如nvoigt提到的,这听起来已经错了。你要做的就是从那里删除lock。仅当您要以独占方式访问某些内容时才使用它。

顺便说一句,“数据不一致”可以通过不需要它们来避免。不要直接使用currentInstruction字段(它是一个字段吗?),但要提供一个线程安全的CurrentInstruction属性。

代码语言:javascript
复制
private object _currentInstructionLock = new object();
private string _currentInstruction
public string CurrentInstruction
{
    get { return _currentInstruction; }
    set
    {
        lock(_currentInstructionLock)
            _currentInstruction = value;
    }
}

另一件事是命名,以_开头的局部变量名称是一种糟糕的风格。一些民族(包括我)使用它们来区分私有字段。属性名称应以BigLetter和局部变量fromSmall开头。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20064618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档