c-多线程程序中的错误(工作缓慢)



我必须制作一个多线程程序(用旋转方法求解方程组)。我的程序给出了正确的答案。但当我创建更多线程时,它运行得更慢。有人能帮我吗?我的部分代码:

typedef struct DATA
{
double *a; 
int n;
int num_thr; 
int total_thr;
int num_row1;
int num_row2;
double cos;
double sin; 
}  DATA;

void synchronize(int total_threads)
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condvar_in = PTHREAD_COND_INITIALIZER;
static pthread_cond_t condvar_out = PTHREAD_COND_INITIALIZER;
static int threads_in = 0;
static int threads_out = 0;
pthread_mutex_lock(&mutex);
threads_in++;
if (threads_in >= total_threads)
{
threads_out = 0;
pthread_cond_broadcast(&condvar_in);
} else
while (threads_in < total_threads)
pthread_cond_wait(&condvar_in,&mutex);
threads_out++;
if (threads_out >= total_threads)
{
threads_in = 0;
pthread_cond_broadcast(&condvar_out);
} else
while (threads_out < total_threads)
pthread_cond_wait(&condvar_out,&mutex);
pthread_mutex_unlock(&mutex);
}
void rotation (double *a,int n, int num_thr,int total_thr,int num_row1,int num_row2,double cos,double sin)
{
int k;
double m;
int first;
first=n-1-num_thr;
for (k=first;k>=num_row1;k=k-total_thr)
{
m=a[num_row1*n+k];
a[num_row1*n+k]=cos*a[num_row1*n+k]+sin*a[num_row2*n+k];
a[num_row2*n+k]=-sin*m+cos*a[num_row2*n+k];
}
synchronize (total_thr);

}
void * rotation_threaded(void *pa)
{
DATA *data=(DATA*)pa ;
rotation(data->a,data->n,data->num_thr,data->total_thr,data->num_row1,data->num_row2,data->cos,data->sin);
return 0;
}

int main(int argc, char * argv[])
{
................

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
n1=a[j*n+i];
m=a[i*n+i];
cos=m/sqrt(m*m+n1*n1);
sin=n1/sqrt(m*m+n1*n1);
for (t=0;t<total_thr;t++)
{
data[t].n=n;
data[t].a=a;
data[t].total_thr=total_thr;
data[t].num_thr=t;
data[t].num_row1=i;
data[t].num_row2=j;
data[t].cos=cos;
data[t].sin=sin;
}
for (k=0;k<total_thr;k++)
{
if (pthread_create (threads+k,0,rotation_threaded,data+k))                  {
printf (" Couldn't create %d thread",k);
return 3;
}
}
for (k=0;k<total_thr;k++)
{
if (pthread_join (threads[k],0))
printf ("Mistake %d n",k);
}
h=b[i];
b[i]=cos*b[i]+sin*b[j];
b[j]=-sin*h+cos*b[j];
} 
}
..............
}

回答特定问题:因为线程在获取锁和等待条件变量上花费的时间比实际工作花费的时间多。多线程并不是一个免费获得更多功率的方案,如果你必须不断地获取高度争用的锁,你将因此受到严重的开销惩罚。你拥有的线程越多,当另一个线程持有锁时,它们就越会争夺锁并被阻塞。

为了解决这个问题:尽量只在必要时同步数据。将大量更改排队,和/或一次做更多的工作,以实际利用CPU上的线程时间。同步时,请尝试仅在最短的绝对必要时间内保持锁定。

最后但同样重要的是:更多的线程可能并不总是更好。如果你有多个线程在处理一个作业队列,通常最好只启动与逻辑CPU内核一样多的线程,这样线程就不必为单个内核而争吵。尽管如此,正确的分析会告诉你问题出在哪里。

根据我所看到的,您为每个(i,j)对重新创建线程,然后等待所有线程完成。

在一开始创建线程并让它们等待一个条件可能会更有意义。然后可以重用这些线程。

您似乎还复制了许多信息,这些信息对于每次迭代中的每个线程都是恒定的(这可能不是速度减慢的原因,但为什么不明确什么是可变的呢)。CCD_ 2中对于每个线程唯一不同的信息是CCD_。na的值从未改变,并且cossinij的值可以保存在for-t循环之外。

synchronize方法有什么用。它似乎在等待所有线程通过threads_in"屏障",然后再通过threads_out"屏障"——但它在保护什么?

最新更新