【发布时间】: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之后立即重新锁定它。