创建线程 - 传递参数

12 c multithreading function parameter-passing

我正在尝试创建多个线程,每个线程计算一个素数.我试图使用线程创建将第二个参数传递给函数.它不断抛出错误.

void* compute_prime (void* arg, void* arg2)
{
Run Code Online (Sandbox Code Playgroud)

这是我的main()与创建线程.&prime_rray [i]在&max_prime给我错误之后.

 for(i=0; i< num_threads; i++)
 {
    primeArray[i]=0;
    printf("creating threads: \n");
    pthread_create(&primes[i],NULL, compute_prime, &max_prime, &primeArray[i]);
    thread_number = i;
    //pthread_create(&primes[i],NULL, compPrime, &max_prime);
 }

 /* join threads */
 for(i=0; i< num_threads; i++)
{
    pthread_join(primes[i], NULL);
    //pthread_join(primes[i], (void*) &prime);
    //pthread_join(primes[i],NULL);
    //printf("\nThread %d produced: %d primes\n",i, prime);
    printf("\nThread %d produced: %d primes\n",i, primeArray[i]);
    sleep(1);
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

myprime.c: In function âmainâ:
myprime.c:123: warning: passing argument 3 of âpthread_createâ from incompatible pointer type
/usr/include/pthread.h:227: note: expected âvoid * (*)(void *)â but argument is of type âvoid * (*)(void *, void *)â
myprime.c:123: error: too many arguments to function âpthread_createâ
Run Code Online (Sandbox Code Playgroud)

如果我拿出第二个参数,它工作正常.

Man*_*rse 21

您只能将一个参数传递给您在新线程中调用的函数.创建一个结构来保存这两个值并发送结构的地址.

#include <pthread.h>
#include <stdlib.h>
typedef struct {
    //Or whatever information that you need
    int *max_prime;
    int *ith_prime;
} compute_prime_struct;

void *compute_prime (void *args) {
    compute_prime_struct *actual_args = args;
    //...
    free(actual_args);
    return 0;
}
#define num_threads 10
int main() {
    int max_prime = 0;
    int primeArray[num_threads];
    pthread_t primes[num_threads];
    for (int i = 0; i < num_threads; ++i) {
        compute_prime_struct *args = malloc(sizeof *args);
        args->max_prime = &max_prime;
        args->ith_prime = &primeArray[i];
        if(pthread_create(&primes[i], NULL, compute_prime, args)) {
            free(args);
            //goto error_handler;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)