search

Home  >  Q&A  >  body text

linux - 为什么用条件变量同步时,发生信号丢失呢?

一个线程自加计数变量,如果被3整除,唤醒另一个等待线程输入该变量。代码如下:

#include <pthread.h>
#include <stdio.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;
int signaled = 0, count = 0;

void* fun1(void* args) {
    for (;;) {
        pthread_mutex_lock(&lock);
        count++;
        if (count % 3 == 0) {
            pthread_cond_signal(&cond);
            if (count > 1000) {
                signaled = 1;
                pthread_mutex_unlock(&lock);
                break;
            }
        }
        pthread_mutex_unlock(&lock);
    }
}

void* fun2(void* args) {
    pthread_mutex_lock(&lock);
    while (!signaled) {
        pthread_cond_wait(&cond, &lock);
        printf("%d\n", count);
    }
    pthread_mutex_unlock(&lock);
}

int main() {
    pthread_t pthid_1, pthid_2;
    pthread_create(&pthid_1, NULL, fun1, NULL);
    pthread_create(&pthid_2, NULL, fun2, NULL);

    void* result;
    pthread_join(pthid_1, &result);
    pthread_join(pthid_2, &result);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&lock);

    return 0;
}

正确结果应该是:3 6 9..... 这样的。
现在的输出是:734 747 762....

大家讲道理大家讲道理2784 days ago687

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:03:48

    Fun1 did not stop after signal(cond), but continued to accumulate count, and the time required for fun2 to recover from the blocking state was enough for count to be modified many times.

    If you want the output to be 3, 6, 9..., you also need to add a synchronization mechanism: wait after fun1 sends signal, wait until fun2 reads and outputs count, and then signal fun1.

    reply
    0
  • Cancelreply