【问题标题】:Issue with pthreads_cond_wait and queue'ing pthreadspthreads_cond_wait 和排队 pthreads 的问题
【发布时间】:2014-08-28 20:49:21
【问题描述】:

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

# 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 上运行它。

【问题讨论】:

  • 当pthread_cond_wait返回时,锁已经被获取。所以你不应该在使用pthread_mutex_lock 之后立即重新锁定它。

标签: c++ windows pthreads


【解决方案1】:

你有两个问题:

  • 条件变量queue_cv 从未发出信号。在将元素推入队列后,您可以使用pthread_cond_signal 发出信号:pthread_cond_signal(&amp;queue_cv);

  • 1234563只需删除pthread_mutex_lock (&amp;queueLock);

注意:

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

【讨论】:

  • 我实际上有一个问题,我进行了 1000 次试验,结果发现无线程版本运行得更快。我觉得好像不应该这样,因为任务是处理数学。我进行了建议的更改,将 while 循环更改为 for 1:1000 循环,并添加了while(!testQueue.empty()){pthread_cond_signal;}。为什么非线程版本比线程版本工作得更快?函数中还有很多打印语句。
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多