Code example – creating any number of threads

So, let's put it to the test: we will write a simple extension of our previous program, this time allowing the user to specify the number of threads to attempt to create within the process as the parameter (ch14/cr8_so_many_threads.c). The main function is as follows:

int main(int argc, char **argv){  long i;  int ret;  pthread_t tid;  long numthrds=0;  if (argc != 2) {      fprintf(stderr, "Usage: %s number-of-threads-to-create\n", argv[0]);      exit(EXIT_FAILURE);  }  numthrds = atol(argv[1]);  if (numthrds <= 0) {      fprintf(stderr, "Usage: %s number-of-threads-to-create\n", argv[0]);      exit(EXIT_FAILURE);  }  for (i = 0; i < numthrds; i++) {        ret = pthread_create(&tid, NULL, worker, (void *)i);        if (ret)              FATAL("pthread_create() ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.