线程退出时重新生成的线程

时间:2012-12-21 09:23:49

标签: c++ multithreading pthreads

我有这个线程化的fcgi应用程序,它会产生N个线程并在退出之前等待它们完成

#include "vips/vips.h"
#include "vips/vips"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "tiff.h"
#include "tiffio.h"
#include "fastcgi.h"
#include "fcgio.h"
#include "Tokenizer.h"
#include "string.h"
#include <sstream>
#include <pthread.h>
#include <sys/types.h>

using namespace std;
using namespace vips;

#define THREAD_COUNT 2
static int counts[THREAD_COUNT];

static void *handleFcgi(void *a)
{
    int rc, i, thread_id = (intptr_t)a;
    pid_t pid = getpid();
    FCGX_Request request;
    char *server_name;

    FCGX_InitRequest(&request, 0, 0);
    for (;;)
    {
        static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;
        static pthread_mutex_t counts_mutex = PTHREAD_MUTEX_INITIALIZER;

        /* Some platforms require accept() serialization, some don't.. */
        pthread_mutex_lock(&accept_mutex);
        rc = FCGX_Accept_r(&request);
        pthread_mutex_unlock(&accept_mutex);

        if (rc < 0 || counts[thread_id] > 5)
            break;

        server_name = FCGX_GetParam("SERVER_NAME", request.envp);

        FCGX_FPrintF(request.out,
                     "Content-type: text/html\r\n"
                     "\r\n"
                     "<title>FastCGI Hello! (multi-threaded C, fcgiapp library)</title>"
                     "<h1>FastCGI Hello! (multi-threaded C, fcgiapp library)</h1>"
                     "Thread %d, Process %ld<p>"
                     "Request counts for %d threads running on host <i>%s</i><p><code>",
                     thread_id, pid, THREAD_COUNT, server_name ? server_name : "?");

        pthread_mutex_lock(&counts_mutex);
        ++counts[thread_id];
        for (i = 0; i < THREAD_COUNT; i++)
            FCGX_FPrintF(request.out, "%5d " , counts[i]);
        pthread_mutex_unlock(&counts_mutex);

        FCGX_Finish_r(&request);
    }

    return NULL;
}

int main (int argc, char **argv)
{
    int i;
    pthread_t id[THREAD_COUNT];
    FCGX_Init();

    for (i = 0; i < THREAD_COUNT; i++)
        pthread_create(&id[i], NULL, handleFcgi, (void*) i);

    pthread_join(id[0], NULL);
    pthread_join(id[1], NULL);

    return(0);
}

我已经将线程设置为在5个请求之后立即完成,因为稍后我会添加一些自定义逻辑,我想在一些请求之后完全重启线程。

我想在每次存在时生成一个线程,这可能吗?

1 个答案:

答案 0 :(得分:1)

简短的回答是,如果让线程退出,则必须生成一个新线程。退出后,您无法重新启动线程,此时系统已拆除线程。您只需要创建一个新主题或保持原来的活着,直到您不需要它为止。

好的,根据您刚刚说过的内容,为什么不考虑使用线程池,比如boost :: threadpool。这将节省以疯狂的速度生成新线程的开销,因为这是一个相当昂贵的操作。

线程池基本上是操作系统所处的线程池,可以用来为其提供工作。这样,您永远不需要创建新线程,您不必担心管理线程,只需将它们交给工作并获得结果即可。