创建线程-传递参数 [英] create thread - passing arguments

查看:114
本文介绍了创建线程-传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting on creating multiple threads that each thread calculates a prime. I am trying to pass a second argument to a function using thread create. It keeps throwing up errors.

void* compute_prime (void* arg, void* arg2)
{

这是我的带有创建线程的main(). & max_prime之后的& primeArray [i]给了我错误.

here is my main() with the create thread. &primeArray[i] after &max_prime is giving me the errors.

 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);
}

我得到的错误是:

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â

如果我删除第二个参数,效果很好.

It works fine if i take out the second argument.

推荐答案

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

You can only pass a single argument to the function that you are calling in the new thread. Create a struct to hold both of the values and send the address of the struct.

#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;
}

这篇关于创建线程-传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆