0

我有一段代码(保存),只能由一个进程一次执行,并成功地用互斥锁保护它。

但是,有一些清理(SavePrep)也在受保护块内部完成,可以长时间运行并且可以在受保护块之外复制。关键是它必须在受保护块内运行,但如果它在轮到它之前在受保护块外运行一点,它将减少在受保护块中花费的时间。(基本上,它要做的准备工作较少。)

现在问题出现了,因为这个 SavePrep 有一个 LOCK 选项。我可以在锁定设置为 FALSE 的情况下在受保护块之外运行它,然后受保护块可以在 LOCK 设置为 TRUE 的情况下同时运行 SavePrep 而不会出现问题。但是,反转不是真的,如果它以 LOCK TRUE 运行,那么以 LOCK FALSE 运行将失败。

所以我想做的是阻止受保护块内的 SavePrep 执行,直到 SavePrep 在受保护块之外开始执行。

这是我在两种情况下都调用的单行代码。无论如何要阻止一行代码开始执行?

我现在正在做的是调用 ReleaseMutex,然后调用 SavePrep。但是,我不确定位于 WaitOne(..) 的下一个进程是否会在 SavePrep 有机会启动之前获得控制权。

有时有多达 20 或 30 个进程在等待的当前外观示例。

    Mutex mutex = new Mutex(false, mutexName);  
    if (mutex.WaitOne(60 * 2 * 1000)  
    {  
        //Can take a while.  Can accept false to not lock if running outside of Wait  
        SavePrep(true);  
        Save();  
        mutex.ReleaseMutex();
    }  

我没有但对以下竞争条件感到担忧:

    Mutex mutex = new Mutex(false, mutexName);  
    if (mutex.WaitOne(60 * 2 * 1000)  
    {  
        //Can take a while.  Can accept false to not lock if running outside of Wait  
        SavePrep(true);  
        Save();  
        mutex.ReleaseMutex();
    }  

    //Simplified.  There is a singleton I've used to keep up with who else is waiting 
    // on the mutex and the SavePrep is actually called with the necessary data for
    // a thread further back in the queue so that when it gets to SavePrep it takes
    // less time.
    //Is there anyway to guarantee this SavePrep call will execute before another
    // enters the WaitOne block?
    SavePrep(false);  
4

0 回答 0