所以我正在尝试编写一个找到素数的程序。该项目的真正目的只是学习多线程。首先,我编写了一个单线程程序,它在 1 分钟内找到了 13,633,943 个。我的多线程版本只有 10,025,627。
这是我的单线程程序代码
#include <iostream>
using namespace std;
bool isprime(long num)
{
long lim = num/2;
if(num == 1)
{
return 0;
}
for(long i = 2; i <= lim; i++)
{
if (num % i == 0)
{
return 0;
}
else{ lim = num/i; }
}
return 1;
}
int main()
{
long lim;
cout << "How many numbers should I test: ";
cin >> lim;
for(long i = 1; i <= lim || lim == 0; i++)
{
if(isprime(i))
{
cout << i << endl;
}
}
}
这是我的多线程程序的代码。
extern"C"
{
#include <pthread.h>
#include <unistd.h>
}
#include <iostream>
using namespace std;
bool isprime(long num);
void * iter1(void * arg);
void * iter2(void * arg);
void * iter3(void * arg);
void * iter4(void * arg);
int main()
{
//long lim;
//cout << "How many numbers should I test: ";
//cin >> lim;
pthread_t t1;
char mem1[4096];//To avoid false sharing. Needed anywhere else?
pthread_t t2;
char mem2[4096];//These helped but did not solve problem.
pthread_t t3;
pthread_create(&t1, NULL, iter1, NULL);
pthread_create(&t2, NULL, iter2, NULL);
pthread_create(&t3, NULL, iter3, NULL);
iter4(0);
}
bool isprime(long num)
{
long lim = num/2;
if(num == 1)
{
return 0;
}
for(long i = 2; i <= lim; i++)
{
if (num % i == 0)
{
return 0;
}
else{ lim = num/i; }
}
return 1;
}
void * iter1(void * arg)
{
for(long i = 1;; i = i + 4)
{
if(isprime(i))
{
cout << i << endl;
}
}
return 0;
}
void * iter2(void * arg)
{
for(long i = 2;; i = i + 4)
{
if(isprime(i))
{
cout << i << endl;
}
}
return 0;
}
void * iter3(void * arg)
{
for(long i = 3;; i = i + 4)
{
if(isprime(i))
{
cout << i << endl;
}
}
return 0;
}
void * iter4(void * arg)
{
for(long i = 4;; i = i + 4)
{
if(isprime(i))
{
cout << i << endl;
}
}
return 0;
}
让我特别困惑的是系统监视器报告单线程的 CPU 使用率为 25%,多线程的使用率为 100%。这不应该意味着它的计算量是原来的 4 倍吗?