线程安全方法的一般形式是:
COPY myfile /tmp/
RUN cp -r /tmp/myfile /target/path/
原因如下:
Type ThreadSafeClass::method (Argument arg
)
{
pthread_mutex_lock(&lock_);
while ( !this->isReady() )
pthread_cond_wait(&someCond_,&lock_);
Type toReturn = doCriticalSection(arg);
pthread_cond_signal(&someOtherCond_);
pthread_mutex_unlock(&lock_);
return(toReturn);
}
一个绝妙的主意:
while ( !this->isReady() )
pthread_cond_wait(&someCond_,&lock_);
为什么在循环之后使用while循环很重要
if ( !this->isReady() )
pthread_cond_wait(&someCond_,&lock_);
打电话吗?
如果while循环早于
pthread_mutex_lock()
通话?
pthread_mutex_lock()
调用的目的是什么?
至此,正在执行pthread_cond_signal()
的线程已完成。什么
通话好吗?
为什么method()
语句在
return(toReturn)
打电话吗?
允许变量pthread_mutex_unlock()
不受保护的是什么?
对于1,我认为这是因为如果我们使用“ toReturn
”,则调用pthread_cond_wait()
的线程可能会虚假地唤醒。
答案 0 :(得分:1)
if
,您将获得A和C之间的竞争条件,但是使用while
,A将在恢复其正常执行之前重新检查该条件。pthread_cond_signal
,您将唤醒该条件变量的等待列表中的第一个线程。答案 1 :(得分:0)
循环而不是单个测试的原因是等待条件变量受spurious wakeup的影响。也就是说,即使未发出条件变量,该等待也可能会返回。据我了解,OS人士坚持这一点,因为允许它可以简化条件变量的实现。