2012-10-30 11 views
7

私は各スレッドが素数を計算する複数のスレッドを作成しようとしています。私はスレッドの作成を使用して関数に2番目の引数を渡そうとしています。それはエラーを投げつけ続ける。スレッド渡し引数を作成する

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

ここでは、スレッドを作成するメイン()です。 & primeArray [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); 
} 

私が手にエラーがある:

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â 

私は2番目の引数を取る場合、それは正常に動作します。

+0

も良いのpthread参照サイトのために[リンク](https://computing.llnl.gov/tutorials/pthreads/#References)チェック、下記答えてご覧ください。 – NickO

答えて

14

新しいスレッドで呼び出す関数に引数を1つだけ渡すことができます。両方の値を保持し、構造体のアドレスを送信する構造体を作成します。

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

のstd ::スレッドの場合には、ユーザは、次の方法でスレッド関数に

のstd ::スレッド(FUNCNAME、ARG1、ARG2)を引数を渡すことができます。例えば

//for a thread function, 
void threadFunction(int x,int y){ 
    std::cout << x << y << std::endl; 
} 

// u can pass x and y values as below 
std::thread mTimerThread; 
mTimerThread = std::thread(threadFunction,1,12);