945a219fb3e5e8d5f4035828723ed70d670b51c0
[catagits/fcgi2.git] / examples / threaded.c
1 /*
2  * threaded.c -- A simple multi-threaded FastCGI application.
3  */
4
5 #ifndef lint
6 static const char rcsid[] = "$Id: threaded.c,v 1.3 1999/07/30 19:09:46 roberts Exp $";
7 #endif /* not lint */
8
9 #include "fcgi_config.h"
10
11 #include <pthread.h>
12
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16
17 #ifdef _WIN32
18 #include <process.h>
19 #endif
20
21 #include "fcgiapp.h"
22
23
24 #define THREAD_COUNT 20
25
26 static int counts[THREAD_COUNT];
27
28 static void *doit(void *a)
29 {
30     int rc, i, thread_id = (int)a;
31     FCGX_Request request;
32     FCGX_Stream *in, *out, *err;
33     FCGX_ParamArray envp;
34     char *server_name;
35
36     FCGX_InitRequest(&request);
37
38     for (;;)
39     {
40         static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;
41         static pthread_mutex_t counts_mutex = PTHREAD_MUTEX_INITIALIZER;
42
43         pthread_mutex_lock(&accept_mutex);
44         rc = FCGX_Accept_r(&in, &out, &err, &envp, &request);
45         pthread_mutex_unlock(&accept_mutex);
46
47         if (rc < 0)
48             break;
49
50         server_name = FCGX_GetParam("SERVER_NAME", envp);
51
52         FCGX_FPrintF(out,
53             "Content-type: text/html\r\n"
54             "\r\n"
55             "<title>FastCGI Hello! (multi-threaded C, fcgiapp library)</title>"
56             "<h1>FastCGI Hello! (multi-threaded C, fcgiapp library)</h1>"
57             "Thread %d<p>"
58             "Request counts for %d threads running on host <i>%s</i><p><code>",
59             thread_id, THREAD_COUNT, server_name ? server_name : "?");
60
61         pthread_mutex_lock(&counts_mutex);
62         ++counts[thread_id];
63         for (i = 0; i < THREAD_COUNT; i++)
64             FCGX_FPrintF(out, "%5d " , counts[i]);
65         pthread_mutex_unlock(&counts_mutex);
66
67         FCGX_Finish_r(&request);
68     }
69
70     return NULL;
71 }
72
73 int main(void)
74 {
75     int i;
76     pthread_t id[THREAD_COUNT];
77
78     FCGX_Init();
79
80     for (i = 1; i < THREAD_COUNT; i++)
81         pthread_create(&id[i], NULL, doit, (void*)i);
82
83     doit(0);
84
85     exit(0);
86 }
87