我想让pthreads一次运行多个实例的功能,以提高运行速度和效率。我的代码应该产生线程,并在队列中有更多项目时保持打开状态。然后这些线程应该做'某事'。代码应该要求“继续?”当队列中没有更多项目时,如果我输入“yes”,则应将项目添加到队列中,并且线程应继续执行“某事”。这是我到目前为止,问题与pthreads_cond_wait和排队pthreads
# 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'立即重新锁定它。 – Brian 2014-08-28 20:58:39