保证与调用pthread_cond_wait和pthread_cond_signal会产生 [英] Guaranteed yielding with pthread_cond_wait and pthread_cond_signal

查看:139
本文介绍了保证与调用pthread_cond_wait和pthread_cond_signal会产生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有3 POSIX线程C程序,共享一个全局变量,互斥和条件变量,其中两个是执行以下伪code:

Assuming I have a C program with 3 POSIX threads, sharing a global variable, mutex, and condition variable, two of which are executing the following psuedocode:

...process data...
pthread_mutex_lock( &mutex );
variable = data_ptr;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );

和第三个运行:

while(1) {
    while( variable == NULL ) {
        pthread_mutex_wait( &cond, &mutex );
    }
    printf( "Data is %d", *variable );
}

它是安全的假设,第三个线程会看到从每个前两个数据?

Is it safe to assume that the third thread will see the data from each of the first two?

把不同的方式,如果一个线程在一个互斥体和条件变量瓦亭,它是安全的假设,这将是如果它标志着下一个得到锁,而不是其他线程可能等待锁?

Put a different way, if a thread is wating on a mutex and a condition variable, is it safe to assume that it will be the next one to get the lock if it is signaled, rather than some other thread that may be waiting on the lock?

推荐答案

有没有这样的事情作为pthread_mutex_wait。我假定你的意思是:

There's no such thing as pthread_mutex_wait. I assume you mean:

pthread_mutex_lock(&mutex);
/* ... */
while (1) {
  while (variable == NULL)
    pthread_cond_wait(&cond, &mutex);
  printf("Data is %d", *variable);
}
/* ... */
pthread_mutex_unlock(&mutex);

有没有机制保障,第三线程将看到从两个数据。调用pthread_cond_signal将唤醒第三个线程,但它可能不会立即采取互斥体。其中一个其他作家的可先取互斥。但是,您可以acheive你想要的东西多一点的工作:

There is no guarentee that the third thread will see the data from both. pthread_cond_signal will awaken the third thread, but it may not take the mutex immediately. One of the other writers may take the mutex first. However you can acheive what you want with a bit more work:

void put(int *p) {
  pthread_mutex_lock(&mutex);
  while (variable)
    pthread_cond_wait(&cond_empty, &mutex);
  variable = p;
  pthread_cond_signal(&cond_full);
  pthread_mutex_unlock(&mutex);
}

int *get() {
  int *ret;

  pthread_mutex_lock(&mutex);
  while (!variable)
    pthread_cond_wait(&cond_full, &mutex);
  ret = variable;
  variable = NULL;
  pthread_cond_signal(&cond_empty);
  pthread_mutex_unlock(&mutex);

  return ret;
}

通过明确地等待要读取的变量,我们避免潜在的竞争状态。

By explicitly waiting for the variable to be read, we avoid the potential race condition.

这篇关于保证与调用pthread_cond_wait和pthread_cond_signal会产生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆