c++ - pthreads_cond_wait 和排队 pthreads 的问题

标签 c++ windows pthreads

我试图让 pthreads 同时运行一个函数的多个实例,以提高运行时速度和效率。我的代码应该产生线程并在队列中有更多项目时保持线程打开。然后那些线程应该做“某事”。该代码应该要求“继续?”当队列中没有更多项目时,如果我键入"is",则应将项目添加到队列中,线程应继续做“某事”。这是我目前所拥有的,

# include <iostream>
# include <string>
# include <pthread.h>
# include <queue>

using namespace std;
# define NUM_THREADS 100

int main ( );
queue<int> testQueue;
void *checkEmpty(void* arg);
void *playQueue(void* arg);
void matrix_exponential_test01 ( );
void matrix_exponential_test02 ( );
pthread_mutex_t queueLock;
pthread_cond_t queue_cv;

int main()
{
    pthread_t threads[NUM_THREADS+1];
    pthread_mutex_init(&queueLock, NULL);
    pthread_cond_init (&queue_cv, NULL);

    for( int i=0; i < NUM_THREADS; i++ )
    {
       pthread_create(&threads[i], NULL, playQueue, (void*)NULL);
    }

    string cont = "yes";
    do
    {
        cout<<"Continue? ";
        getline(cin, cont);
        pthread_mutex_lock (&queueLock);
        for(int z=0; z<10; z++)
        {

           testQueue.push(1);

        }
        pthread_mutex_unlock (&queueLock);
    }while(cont.compare("yes"));

    pthread_mutex_destroy(&queueLock);
    pthread_cond_destroy(&queue_cv);
    pthread_exit(NULL);
    return 0;
}

void* checkEmpty(void* arg)
{
    while(true)
    {
        pthread_mutex_lock (&queueLock);
        if(!testQueue.empty()){
            pthread_cond_signal(&queue_cv);}
        pthread_mutex_unlock (&queueLock);
    }
    pthread_exit(NULL);
}

void* playQueue(void* arg)
{
    while(true)
    {
        pthread_cond_wait(&queue_cv, &queueLock);
        pthread_mutex_lock (&queueLock);
        if(!testQueue.empty())
        {
            testQueue.pop();
            cout<<testQueue.size()<<endl;
        }
        pthread_mutex_unlock (&queueLock);
    }
    pthread_exit(NULL);
}

所以我的问题在于代码进入死锁这一事实,我无法弄清楚问题发生在哪里。我不是多线程的老手,所以我很容易在这里犯错误。我也在 Windows 上运行它。

最佳答案

你有两个问题:

  • 条件变量 queue_cv 永远不会发出信号。在将元素插入队列后,您可以使用 pthread_cond_signal 向其发送信号:pthread_cond_signal(&queue_cv);

  • playQueue 中,您尝试在从 pthread_cond_wait 返回后获取锁:因为您的互斥锁不可重入,这是未定义的行为(这可能是你的僵局的来源)。只需删除 pthread_mutex_lock (&​​queueLock);

注意:

我不确定它的真正目的是什么,但是从未调用过 checkEmpty() 方法

关于c++ - pthreads_cond_wait 和排队 pthreads 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25557777/

相关文章:

c++ - 在 Windows 8.1 中查找触摸数字化仪的物理尺寸

c - 如何将参数传递给 ZwCreateThreadEx 例程?

windows - Windows 上的 Git 不要求 SSH key 密码,或使用 SSH key

c - 警告 : unused parameter ‘data’ when creating a new thread

c++ - 用于保存客户信息的线程安全数据结构

匹配任何类型参数的 C++ 可变参数模板模板参数

c++ - 将 uint32_t 转换为 uint64_t 会产生不同的值?

c++ - 如何在类函数中创建线程?

c++ - VS2015 预览 : NDK_ROOT is not defined

c++ - "doesn' t synthesize"和 "defined as deleted"有什么区别?