1

我有这个线程化的 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 个请求后完成,因为稍后我将添加一些自定义逻辑,并且我想在一些请求后完全重新启动线程。

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

4

1 回答 1

1

简短的回答是,如果您让线程退出,则必须生成一个新线程。一旦线程退出,您将无法重新启动线程,此时系统已拆除该线程。您只需要创建一个新线程或保持原始线程处于活动状态,直到您不需要它。

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

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

于 2012-12-21T09:32:53.640 回答