2012-10-30 15 views
7

मैं कई धागे बनाने का प्रयास कर रहा हूं कि प्रत्येक थ्रेड एक प्राइम की गणना करता है। मैं धागे बनाने का उपयोग कर एक समारोह में एक दूसरा तर्क पारित करने की कोशिश कर रहा हूँ। यह त्रुटियों को फेंकता रहता है।थ्रेड बनाएं - गुजरने वाले तर्क

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

यहां मेरा मुख्य() बनाने धागे के साथ है। & प्राइमएरे [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â 

यह ठीक काम करता है अगर मैं दूसरा तर्क बाहर ले।

+0

नीचे का जवाब देखने के लिए, यह भी एक अच्छा pthread संदर्भ साइट के लिए बाहर [कड़ी] (https://computing.llnl.gov/tutorials/pthreads/#References) की जाँच करें। – NickO

उत्तर

14

आप केवल उस फ़ंक्शन को एक ही तर्क दे सकते हैं जिसे आप नए धागे में बुला रहे हैं। दोनों मानों को पकड़ने और संरचना का पता भेजने के लिए एक संरचना बनाएं।

#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); 
संबंधित मुद्दे