C 如何使我的双线程程序工作得更快?
我写了一个计算素数的程序。首先,我编写了“常规”代码,效果很好,但我想让计算速度更快,所以我决定将计算分成两个线程,同时进行计算。这两个线程都与互斥体同步,但速度大约是我的单线程版本的4-5倍。代码如下:C 如何使我的双线程程序工作得更快?,c,multithreading,C,Multithreading,我写了一个计算素数的程序。首先,我编写了“常规”代码,效果很好,但我想让计算速度更快,所以我决定将计算分成两个线程,同时进行计算。这两个线程都与互斥体同步,但速度大约是我的单线程版本的4-5倍。代码如下: #include <pthread.h> #include <stdio.h> unsigned long isqrt(unsigned long x) //function to calculate sqrt of int, not mine { re
#include <pthread.h>
#include <stdio.h>
unsigned long isqrt(unsigned long x) //function to calculate sqrt of int, not mine
{
register unsigned long op, res, one;
op = x;
res = 0;
one = 1 << 30;
while (one > op) one >>= 2;
while (one != 0)
{
if (op >= res + one)
{
op -= res + one;
res += one << 1;
}
res >>= 1;
one >>= 2;
}
return res;
}
static unsigned long long n;
pthread_mutex_t lock;
pthread_mutex_t lock1;
void *threadFunc(void *arg)
{
unsigned long long num, x, a, b = 0, sqrtNum;
for(num = 3; num <= n; num += 4)
{
a = 0;
sqrtNum = isqrt(num);
for(x = 3; x <= sqrtNum; x += 2)
if(num % x == 0)
a++;
pthread_mutex_lock(&lock1);
if(a == 0)
printf("%llu\n", num);
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void)
{
pthread_t pth;
unsigned long long num, x, a, b = 0, sqrtNum;
char buff[21];
fgets(buff, 21, stdin);
sscanf(buff, "%llu", &n);
pthread_mutex_init(&lock, NULL);
pthread_mutex_init(&lock1, NULL);
pthread_create(&pth,NULL,threadFunc,"foo");
for(num = 1; num <= n; num += 4)
{
a = 0;
sqrtNum = isqrt(num);
for(x = 3; x <= sqrtNum; x += 2)
if(num % x == 0)
a++;
pthread_mutex_lock(&lock);
if(a == 0)
printf("%llu\n", num);
pthread_mutex_unlock(&lock1);
}
pthread_mutex_destroy(&lock);
pthread_mutex_destroy(&lock1);
pthread_cancel(pth);
return 0;
}
#包括
#包括
unsigned long isqrt(unsigned long x)//用于计算int的sqrt的函数,而不是我的
{
寄存器无符号长op,res,1;
op=x;
res=0;
一个=1 op)一个>>=2;
而(一!=0)
{
如果(op>=res+one)
{
op-=res+1;
res+=1>=1;
一个>>=2;
}
返回res;
}
静态无符号长n;
pthread_mutex_t lock;
pthread_mutex_t lock1;
void*threadFunc(void*arg)
{
无符号long-long-num,x,a,b=0,sqrtNum;
对于(num=3;num为什么要锁定互斥体?否则,结果会混淆,即:有互斥体:1,2,3,5,7,11,13,17,19…没有互斥体:1,3,11,7,19,13,17。是的,但这就是想法。现在你可能正在对线程进行sinchronizing,使它们像一个线程一样工作,但切换会使它们变慢。你可以将它们放入一个数组并对t进行排序如果您愿意,请在末尾折边。通信/同步开销。紧密耦合的线程通常比单个线程慢。可以通过在线程之间清晰地分割作业来放松耦合,使用生产者/消费者模式,或者使用单个线程。@Мааааааааааааааа。