Please disable adblock to view this page.

← Go home

Passing command line arguement to thread functions (C++)

April 24, 2016
Published By : Pratik Kataria
Categorised in: ,

/*
Write object oriented program using C++ for passing command line arguement to 
thread functions and using command line arguement to determine number of threads
to be created. Use multicore programming.
*/
/*Execution:
oct@CCOMPL08-10:~$ g++ multicore1.cpp -lpthread
oct@CCOMPL08-10:~$ ./a.out 5 5
*/

#include<iostream>
#include<pthread.h>
#include<stdlib.h>

using namespace std;

void * display(void *param){ //Note the void* and parameter's void*

    cout<<"Thread created...\n";
    cout<<(char*) param<<"\n";

}

int main(int argc, char * argv[])
{

    pthread_t tid[5];
    
    for(int i=0; i<atoi(argv[1]);i++){//C function atoi helps convert (char*) to int
        pthread_create(&tid[i], NULL, display, (void *) argv[2]);
    }
    
    for(int j=0; j<atoi(argv[1]);j++){
        pthread_join(tid[j], NULL); //Here NULL is the return code which is given.
    }
    
    return 0;

}

View Article Page
Download