C#与AutoResetEvent的线程问题

cod*_*nix 6 c# multithreading locking thread-safety autoresetevent

如何正确同步?目前有可能SetDatae.WaitOne()完成后调用,因此d可能已经设置为另一个值.我试图插入锁,但它导致死锁.

AutoResetEvent e = new AutoResetEvent(false);

public SetData(MyData d)
{
   this.d=d;
   e.Set();    // notify that new data is available
}

// This runs in separate thread and waits for d to be set to a new value
void Runner() 
{    
   while (true)
   {
      e.WaitOne();  // waits for new data to process
      DoLongOperationWith_d(d);
   }
}
Run Code Online (Sandbox Code Playgroud)

最好的解决方案是引入一个dataAlreadyBeenSetAndWaitingToBeProcessed设置SetData为true 的新布尔变量,并在其结尾处DoLongOperationWith_d设置为true,因此如果SetData调用此变量设置为true,它可能只返回?

Sam*_*ron 5

这是未经测试的,但使用基于.net的原语是一种优雅的方法:

class Processor<T> {
    Action<T> action;
    Queue<T> queue = new Queue<T>();

    public Processor(Action<T> action) {
        this.action = action;
        new Thread(new ThreadStart(ThreadProc)).Start();
    }

    public void Queue(T data) {
        lock (queue) {
            queue.Enqueue(data);
            Monitor.Pulse(queue); 
        }            
    }

    void ThreadProc() {
        Monitor.Enter(queue);
        Queue<T> copy;

        while (true) {                 
            if (queue.Count == 0) {
                Monitor.Wait(queue);
            }

            copy = new Queue<T>(queue);
            queue.Clear();
            Monitor.Exit(queue);

            foreach (var item in copy) {
                action(item); 
            }

            Monitor.Enter(queue); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例程序:

class Program {

    static void Main(string[] args) {

        Processor<int> p = new Processor<int>((data) => { Console.WriteLine(data);  });
        p.Queue(1);
        p.Queue(2); 

        Console.Read();

        p.Queue(3);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个非队列版本,可能首选队列版本:

object sync = new object(); 
AutoResetEvent e = new AutoResetEvent(false);
bool pending = false; 

public SetData(MyData d)
{
   lock(sync) 
   {
      if (pending) throw(new CanNotSetDataException()); 

      this.d=d;
      pending = true;
   }

   e.Set();    // notify that new data is available
}

void Runner() // this runs in separate thread and waits for d to be set to a new value
{

     while (true)
     {

             e.WaitOne();  // waits for new data to process
             DoLongOperationWith_d(d);
             lock(sync) 
             {
                pending = false; 
             }
     }
}
Run Code Online (Sandbox Code Playgroud)