create thread - passing arguments create thread - passing arguments multithreading multithreading

create thread - passing arguments


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 10int 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;}


In case of std::thread, the user can pass arguments to the thread function in the following method

std::thread(funcName,arg1,arg2);

for instance,

//for a thread function, void threadFunction(int x,int y){   std::cout << x << y << std::endl;}// u can pass x and y values as belowstd::thread mTimerThread;mTimerThread = std::thread(threadFunction,1,12);


This is the code of Manakarse , everything is really good but you need a

pthread_join(thread[i],NULL)

just to be sure all of threads will successfully execute before end of main thread("main will "waiting" while all of threads aren't finished yet);