我试图理解线程。我正在尝试让多个线程计算素数。我希望一个线程计算第一个数字,然后让下一个线程计算下一个数字,依此类推,然后无论哪个线程找到素数打印它。
因此,从 1 到 50 开始。将新数字传递给新线程。我认为这就是我们想要的。
继承人我到目前为止。
void* compute_prime (void* arg)
{
//pthread_mutex_lock(&lock);
int candidate = 2;
int n = *((int*) arg);
while (1) {
int factor;
int is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor < candidate; ++factor)
if (candidate % factor == 0) {
is_prime = 0;
break;
}
/* Is this the prime number we're looking for? */
if (is_prime) {
if (--n == 0)
/* Return the desired prime number as the thread return value. */
return (void*) candidate;
}
++candidate;
}
return NULL;
}
int main ()
{
int which_prime = 50;
int isPrime1, isPrime2, isPrime3, isPrime4;
fprintf (stderr, "main thread pid is %d\n", (int) getpid ());
for(master_list; master_list < which_prime; master_list++)
{
//do{
// pthread_mutex_lock(&lock);
pthread_create (&thread1, NULL, &compute_prime, &master_list);
//master_list++;
//pthread_mutex_unlock(&lock);
//}while(master_list < which_prime);
}
return 0;
}
我的输出。
main thread pid is 508
Thread1 Found the prime number: 3.
Thread2 Found the prime number: 3.
Thread3 Found the prime number: 3.
Thread4 Found the prime number: 3.
Thread1 Found the prime number: 7.
Thread2 Found the prime number: 7.
Thread3 Found the prime number: 7.
Thread4 Found the prime number: 7.
Thread1 Found the prime number: 13.
Thread2 Found the prime number: 13.
Thread3 Found the prime number: 13.
Thread4 Found the prime number: 13.
ETC....
这有点是我想要的。但不是每个线程都应该找到相同的素数。他们应该找到不同的素数。即使我在线程之前增加变量,它仍然无法工作。我注释掉了我试图让它工作的代码。我需要做什么?我希望我很清楚。