简体   繁体   中英

Creating threads in a loop

Is it bad to create threads in loop, like that?

Thread function example:

void *thread_func(void* args)
{
  const char *str = (const char *)args;

  printf("Threading %s\n", str);
  usleep(1000);
}

Main loop:

pthread_t thread;
while (1) {
    char *str = "test str";
    if (pthread_create(&thread, NULL, thread_func, str)) {
            fprintf(stderr, "Failed to create thread\n");
            return -1;
    }
    usleep(3000);
  /* Thread guaranteed finished here */
  }

Or I must create it once and reuse in loop

Your code is not correct. While it is okay to re-use a pthread_t variable, you should join every thread. Otherwise, your system might run out of resources rather quickly.

The assumption that the thread is “guaranteed to have finished” after sleeping for any amount of time is also not correct. (Besides, if you're going to sleep on the main thread until the worker thread finished, why did you create a separate thread in the first place?)

So, the general approach to have n threads do work is to create an array of n thread handles, start a thread for each one, then do whatever the main thread is supposed to do in the mean time and finally join all threads.

#include <stdio.h>
#include <pthread.h>

#define NTHREADS 10

void * thread_func(void * args);

int
main()
{
  pthread_t threads[NTHREADS];
  void * retvals[NTHREADS];
  int count;
  for (count = 0; count < NTHREADS; ++count)
    {
      if (pthread_create(&threads[count], NULL, thread_func, "...") != 0)
        {
          fprintf(stderr, "error: Cannot create thread # %d\n", count);
          break;
        }
    }
  for (int i = 0; i < count; ++i)
    {
      if (pthread_join(threads[i], &retvals[i]) != 0)
        {
          fprintf(stderr, "error: Cannot join thread # %d\n", i);
        }
    }
}

Creating a thread once and reusing it is definitely a better idea, because thread creation itself consume CPU resource. With this piece of code, the thread creation will start failing after sometime. The reason is, if we do not join a thread that is join-able, it ends up as a zombie thread which consumes some system resources. So we can say that with this piece of code, we are leaking some system resources in each iteration and eventually the system will reach a state where it will not have enough resources required to create a thread. This problem can be avoided by adding a call to pthread_join before "usleep(3000)" statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM