pthread条件变量一次只能使用吗?

时间:2018-04-27 20:41:32

标签: c multithreading pthreads mutex condition-variable

我正在学习使用pthreads,互斥量和条件变量,但事情并没有按预期进行。

MAIN THREAD:连续运行,发出工作线程信号,从file_A读取。

WORKER THREAD:睡眠,直到收到信号,写入file_A,重新进入睡眠状态(应该是可重复的)

所以我理解这里需要一个互斥锁来阻止两个线程读取/写入同一个文件。我使用条件变量来通知工作线程。

但由于某种原因,工作线程只运行一次。我是否需要重置条件变量或执行其他操作?

工作线程函数:

void* WriteTime(){
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&condition, &mutex);

    /* Open File, Write to File, Close File */

    pthread_mutex_unlock(&mutex);
}

主线程:

pthread_t timeThread;
pthread_create(&timeThread, NULL, &WriteTime, NULL);

while(gameConditionFulfilled == false){
    /* Print status, gets user input into line */

    /* If user enters "time", wake up WORKER_THREAD */

    if(strcmp(line, "time")==0){
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&condition);

        /* Read from file, print data, close file */ 

        pthread_mutex_unlock(&mutex);
    }
}

我对上述代码的理解也是这样的:

  1. 工作线程锁定互斥锁。 (在主要循环之前推出)
  2. 工作线程cond_wait解锁互斥锁并等待条件。
  3. 主线程锁定互斥锁。
  4. 主线程信号状况。
  5. 工作线程重新获得互斥锁,写入文件。
  6. 工作线程解锁互斥锁。
  7. 主线程重新获得互斥锁并将其锁定。
  8. 主线程读取文件。
  9. 主线程解锁互斥锁。
  10. 工人线程重获锁定?
  11. 行为实际上是:

    1. 主线程从文件中读取
    2. 工作线程唤醒,写入文件,永不再次运行

1 个答案:

答案 0 :(得分:1)

首先,你需要在WriteTime()中使用某种循环 - 返回会导致调用pthread_exit()。当pthread_create()启动一个线程时,它就像是:

一样启动
pthread_exit((*func)(arg));

这引出了第二点 - 你的编译器应该对此尖叫,因为你的WriteTime()没有返回任何东西。警告很有用;他们不需要服从,但你应该理解他们为什么被提出来。

要跳过几章,条件变量的概念是保护“条件”;例如,有数据准备读或写。您使用它们就像信号量一样,但与信号量不同,条件变量没有任何内存。只有在线程等待时调用pthread_condition_(signal | broadcast)()时,Pthread_condition_wait()才会返回。如果在没有人等待时调用pthread_condition_signal(),则不会发生任何事情。所以条件变量的习惯用法是:

lock(mutex)
while (something_hasn’t_happened) {
    wait(cond, mutex)
}
do something
unlock(mutex)
相关问题