-1

I was asked to create a program that starts from the command line with an arg that defines how many threads that shall be created, and every thread that been created shall print out its number. I have just started with the threading so please bear with me!

I know learn how to create threads but only predefine nr in the program but how to take the arg from user input? i don't really know how to go about the problem.

aydinugur
  • 1,208
  • 2
  • 14
  • 21

1 Answers1

1

The argument can be taken from the entry point of the C application. In the following example, I check if the argument count is 2. The first argument is the name of the program itself, the second being the count of threads you'd like to create.

int main(int argc, char *argv[]) {
    if(argc != 2) {
        return 0;
    }

    // Convert the string (char *) to an int with a base of 10
    int threads = strtol(argv[1], NULL, 10);

    for(int i = 0; i < threads; i++) {
        // Create thread
    }

    return 0;
}
  • int main(int argc, const char * argv[]) { if(argc != 2) { return 0; } // Convert the string (char *) to an int with a base of 10 long int threads = strtol(argv[1], NULL, 10); pthread_t threadsTOcreate [threads]; for(int i = 0; i < threads; i++) { pthread_create(&threadsTOcreate[i], NULL,NULL, &threads); printf("my number is %d",i); } // wait until thread is done for (int i = 0; i < threads ; i++) { pthread_join(threadsTOcreate[i], NULL); } return 0; } – Haidar Wahid Oct 30 '17 at 22:36