简体   繁体   English

循环创建线程

[英]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. 虽然可以重新使用pthread_t变量,但是您应该加入每个线程。 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. 因此,让n个线程起作用的一般方法是创建一个由n个线程句柄组成的数组 ,为每个线程句柄启动一个线程,然后同时执行主线程应做的所有事情,最后加入所有线程。

#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. 一次创建一个线程并重新使用它绝对是一个更好的主意,因为线程创建本身会消耗CPU资源。 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. 可以通过在“ usleep(3000)”语句之前添加对pthread_join的调用来避免此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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