pthread_cond_broadcast没有在POSIX忙等待

时间:2013-09-30 08:58:13

标签: c multithreading pthreads posix

我是多线程的新手并且遇到了分段错误。我正在使用

void addfunction(void *xyz)
{
    flag_TO_go = 1;
    pthread_cond_broadcast(&check_Queue2);
    pthread_mutex_unlock(&get_mutex);
}

void delete_thread(void *abc)
{
    while(1){
        pthread_mutex_lock(&get_mutex);
        while (!flag_TO_go ) {//condition variable
            pthread_cond_wait(&check, &get_mutex);
        }
        flag_To_go= 1;
        //things to do
        //delete elemenst from a linked list
        pthread_mutex_unlock(&get_mutex);
    }
}

我得到的是分段错误,因为我的列表在第一个元素删除后没有任何元素。但我的线程是获取锁并检查它  还有其他方法可以使用cond wait。

如果有人能在没有繁忙等待的情况下建议一种方法吗?

2 个答案:

答案 0 :(得分:1)

flag_TO_go = 1中设置addfunction之前,您需要锁定互斥锁。

如果要做的事情真的意味着从列表中取出项目,也许您应该检查非空列表而不是使用flag_TO_go变量。

另外,在两个函数中将标志设置为1,我不明白这一点。你确定这是对的吗?

答案 1 :(得分:0)

试试这个..

void addfunction(void *xyz)
{
    pthread_mutex_lock(&get_mutex);
    flag_TO_go = 1;
    pthread_cond_broadcast(&check_Queue2);
    pthread_mutex_unlock(&get_mutex);
}

void delete_thread(void *abc)
{
    while(1){
        pthread_mutex_lock(&get_mutex);
        while (!flag_TO_go ) {//condition variable
            pthread_cond_wait(&check, &get_mutex);
        }
        flag_To_go= 0;
        //things to do
        //delete elemenst from a linked list
        pthread_mutex_unlock(&get_mutex);
    }
}