0

线性化顺序是如何确定的。怎么能说下面代码的线性化顺序就是wait()释放的顺序。如何检查代码是否可线性化?

class Buffer
{
    int in = 0;
    int out = 0;
    int numElems = 0;

    synchronized void put(E elem) throws InterruptedException
    {
        while (!numElems < N)
        {
            wait();
        }
        buff[in] = elem;
        in = (in + 1) % N;
        notifyAll();
    }

    synchronized E take() throws InterruptedException
    {
        while (!numElems > 0)
        {
            wait();
        }
        E temp = buff[out];
        out = (out + 1) % N;
        return temp;
        notifyAll();
    }
}
4

1 回答 1

1

这里只有一个锁(一个特定Buffer对象上的锁),所以线性化顺序就是获取锁的顺序(或释放 - 它是相同的顺序)。锁总是在进入时释放wait并在退出时获得wait,这就是为什么您在此上下文中听说过wait释放顺序的原因。

我不确定“检查它是否可线性化”是什么意思。如果您的意思是任何并行执行都等效于某些串行排序,那么这里很明显(尽管通常很难),因为对内存的所有访问都在一个锁下,因此实际上没有并行执行。

于 2010-12-11T05:12:32.863 回答