pthread_cond_signal无法唤醒pthread_cond_wait

狄摩西尼 发布于 2016/09/19 15:29
阅读 573
收藏 0

请问,有人遇到pthread_cond_signal无法唤醒pthread_cond_wait的问题了吗?

glibc库版本是2.4,内核版本是3.10.18,CPU是ARM CPU单核,运行下面的测试程序几分钟内会出现,在MIPS平台运行一个小时没有出现问题。感觉是ARM处理器的glibc库或者Linux内核存在缺陷。

下面是测试程序:

#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/stat.h>


static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


/* 苹果的数量 */
static int apples;


/* 生产苹果的线程 */
static void *thread_fn(void *arg)
{
    prctl(PR_SET_NAME, "test_sender");


    while(1) {
        pthread_mutex_lock(&mutex);
        if (apples < 256) {
            apples++;
        }
        pthread_mutex_unlock(&mutex);


        pthread_cond_signal(&cond);
        //pthread_cond_broadcast(&cond);
    }


    return NULL;
}


int main(void)
{
    int ret;
    pthread_t thread;
    unsigned int before_wait, after_wait;
    int fd;


    prctl(PR_SET_NAME, "test_recver");
    fd = open("/data/pthread_cond_t.txt",
        O_RDWR | O_CREAT | O_TRUNC,
        S_IRWXU | S_IRWXG | S_IRWXO);
    if (fd >= 0) {
        char buf[100];


        snprintf(buf, sizeof(buf), "&cond.__data.__futex=%p.\n",
            &cond.__data.__futex);
        write(fd, buf, strlen(buf));
        close(fd);
    }
           
    ret = pthread_create(&thread, NULL, thread_fn, NULL);
    if (ret != 0) {
        return EXIT_FAILURE;
    }


    before_wait = after_wait = 0;
    /* 消费苹果 */
    while(1) {
        pthread_mutex_lock(&mutex);
        while(apples == 0) {
            before_wait++;
            fd = open("/data/pthread_cond_wait.txt",
                O_RDWR | O_CREAT | O_TRUNC,
                S_IRWXU | S_IRWXG | S_IRWXO);
            if (fd >= 0) {
                char buf[100];


                snprintf(buf, sizeof(buf), " before_wait=%u, after_wait=%u.\n",
                    before_wait, after_wait);
                write(fd, buf, strlen(buf));
                close(fd);
            }


            pthread_cond_wait(&cond, &mutex);


            after_wait++;
            fd = open("/data/pthread_cond_wait.txt",
                O_RDWR | O_CREAT | O_TRUNC,
                S_IRWXU | S_IRWXG | S_IRWXO);
            if (fd >= 0) {
                char buf[100];


                snprintf(buf, sizeof(buf), " before_wait=%u, after_wait=%u.\n",
                    before_wait, after_wait);
                write(fd, buf, strlen(buf));
                close(fd);
            }
        }
        apples--;
        pthread_mutex_unlock(&mutex);
    }


    return 0;
}


连续执行cat /data/pthread_cond_wait.txt,过几分钟,会发现before_wait和after_wait的值停止不动。

加载中
返回顶部
顶部