[英]How to pass the argument in pthread_create to function?
The point is use multithread to find the prime numbers, In this case I use 2 of thread the first one is find a prime in range of (0,1000) and the second thread in range of (1000,2000) But the program is can't run as I wish, I think the argument in pthread_create to the function is a problem关键是使用多线程来查找素数,在这种情况下,我使用 2 个线程,第一个是在 (0,1000) 范围内查找素数,第二个线程在 (1000,2000) 范围内查找,但程序是无法按我的意愿运行,我认为在 pthread_create 中对 function 的参数是一个问题
void *findprime(void *args){
int i,j,temp=0;
int count = 0;
int n = *((int*)args);
if (n==1000) {temp = 1;}
if (n==2000) {temp = 1000;}
for (i = temp; i <= n; i++)
{
count = 0;
for (j = temp; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
if (count == 2)
{
printf("%d ", i);
}
}
return NULL;
}
int main () {
pthread_t t_1, t_2, t_3, t_4, t_5;
int t_1args = 1000;
int t_2args = 2000;
printf("Before Using Thread \n");
pthread_create(&t_1, NULL , findprime, (void *)&t_1args);
pthread_create(&t_2, NULL , findprime, (void *)&t_2args);
pthread_join(t_1, NULL);
pthread_join(t_2, NULL);
printf("After Thread \n");
exit(0);
}
The problem is not with the arguments, they seem to be fine.问题不在于 arguments,它们似乎很好。 The problem is with the loop counting the dividers:
问题在于循环计算除法器:
for (j = temp; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
In the second thread, what temp is initialized to?在第二个线程中,将 temp 初始化为什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.