【发布时间】:2014-10-28 03:22:15
【问题描述】:
我试图在多个 pthread 上运行一个函数以提高效率和运行时间。该函数执行大量矩阵计算和打印语句。但是,当我运行测试以查看性能改进时,单线程代码运行得更快。
我的测试如下:
-对于单线程:运行一个调用函数的for循环1:1000。
-对于多线程:生成 100 个 pthread,有一个包含 1000 个项目的队列和一个 pthread_cond_wait,并让线程运行该函数,直到队列为空。
这是我的 pthread 代码(单线程只是一个 for 循环):
# include <iostream>
# include <string>
# include <pthread.h>
# include <queue>
using namespace std;
# define NUM_THREADS 100
int main ( );
queue<int> testQueue;
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];
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);
}
pthread_mutex_lock (&queueLock);
for(int z=0; z<1000; z++)
{
testQueue.push(1);
pthread_cond_signal(&queue_cv);
}
pthread_mutex_unlock (&queueLock);
pthread_mutex_destroy(&queueLock);
pthread_cond_destroy(&queue_cv);
pthread_cancel(NULL);*/
return 0;
}
void* playQueue(void* arg)
{
bool accept;
while(true)
{
pthread_cond_wait(&queue_cv, &queueLock);
accept = false;
if(!testQueue.empty())
{
testQueue.pop();
accept = true;
}
pthread_mutex_unlock (&queueLock);
if(accept)
{
runtest();
}
}
pthread_exit(NULL);
}
我的直觉告诉我,多线程版本应该跑得更快,但事实并非如此。有什么原因,还是我的代码有问题?我在 Windows 上使用 C++,必须下载一个库才能使用 pthread。
【问题讨论】:
-
您的
playQueue被声明为返回一个指针,但代码不返回任何值。那是未定义的行为。此外,您的代码中有一个*/与/*不匹配 另外,您有 100 个 cpu(核心)吗?否则,即使您的程序是并行的,大多数线程也会在队列中等待并浪费同步开销。 -
playQueue实际上并没有做任何工作。您正在测量创建和拆除线程的纯开销。 -
@IgorTandetnik 抱歉我抄错了,但我编辑了这个问题。该线程应该执行函数 runtest() ,其中包含所有数学。
-
在担心让您的程序快速运行之前,您需要先使其正确。有两个未定义行为的来源:(1)
playQueue调用pthread_cond_wait而不首先锁定互斥体,以及 (2)main销毁互斥体和条件变量而不等待线程完成。 -
你不应该运行很多线程。 100 几乎总是过高。尝试运行比核心多一点的线程(即在 Linux 上
grep processor /proc/cpuinfo| wc -l...的结果)。所以尝试使用 5、10、15 和 20 线程。
标签: c++ multithreading performance pthreads