简体   繁体   English

如何将 pthread_create 中的参数传递给 function?

[英]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.

相关问题 如何将参数和函数传递给pthread_create - How to pass parameters and function to pthread_create 如何将字符串类型的向量元素作为参数传递给pthread_create()? - How to pass a vector element of type string as argument to pthread_create()? 将数组列表作为参数传递给 pthread_create - Pass an array list as an argument to pthread_create 如何在同一个函数上编写 pthread_create ? - how to write pthread_create on the same function? 为什么必须将&#39;this&#39;指针作为&#39;arg&#39;参数传递给pthread_create - Why is it necessary to pass the 'this' pointer as 'arg' argument to pthread_create pthread_create() 调用的函数的多个参数 - 参数是函数指针 - Multiple arguments to function called by pthread_create() - argument is function pointer pthread将对象作为参数传递给pthread_create - pthread passing object as argument to pthread_create Pthread_create似乎刷新了传递给输入函数的参数 - Pthread_create seems to flush the argument passed to the input function 为什么我们在pthread_create中将函数参数作为void *传递? - Why do we pass function arguments as void* in pthread_create? 如何在C ++中的pthread_create中正确传递具有函数成员的结构指针 - how to properly pass a struct pointer having a function member in pthread_create in c++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM