两个线程,一个共享属性。读者/作家困境

时间:2013-09-30 21:21:55

标签: c# multithreading locking

我有简单的问题,但仍然找不到合适的解决方案(C#)

  1. 假设我在主类中运行主线程,不时使用某些资源char[] arena_snapshot(解析它,根据此更新竞技场)。
  2. 此外,我启动了工作线程,不断更新共享资源char[] arena_snapshot
  3. 是否有可能在解析工作线程的过程中修改缓冲区,以便主线程错误地解析缓冲区。 如何在解析时锁定arena_snapshot?

    class Arena
    {
        List<PLayer> players;
        ...
        public int main()
        {
            arenaClient = new ArenaClient();
            Thread arenaListener = new Thread(new ThreadStart(arenaClient.StartListener));
            arenaListener.IsBackground = true;
            arenaListener.Start(); //Start UDP worker
        }
    
        public void Update()
        {
            //Let's parse the buffer and update our Arena ..
            ...
            foreach (Player p in players)
            {
    
                play.Position.X = arenaClient.arena_snapshot[2];
                //etc...
            }
    
        }
    }
    
    class ArenaClient
    {
        ...
        public char[] arena_snapshot; //hold most recent information about our Arena (snapshot)
        ...
        public void StartListener()
        {
            while(!done)
            {
                ...
                //Warning! Updating the snapshot, warn the main thread! Don't do this during parsing of the snapshot!
                arena_snapshot = UDPClient.Receive(ref groupEP);;
                ...
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

您是否尝试过lock

    private Object thisLock = new Object();
    private char[] _arena_snapshot;
    public char[] arena_snapshot
    {
        get
        {
            lock (thisLock)
            {
                return _arena_snapshot;
            }
        }

        set
        {
            lock (thisLock)
            {
                _arena_snapshot = value;
            }
        }
    }