efa00da634ac964639a5a0a30d11c3dc9f2738bf
[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.7 1999/08/10 14:40:32 roberts Exp $";
7 #endif /* not lint */
8
9 #include "fcgi_config.h"
10
11 #include <pthread.h>
12 #include <sys/types.h>
13
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17
18 #ifdef _WIN32
19 #include <process.h>
20 #endif
21
22 #include "fcgiapp.h"
23
24
25 #define THREAD_COUNT 20
26
27 static int counts[THREAD_COUNT];
28
29 static void *doit(void *a)
30 {
31     int rc, i, thread_id = (int)a;
32     pid_t pid = getpid();
33     FCGX_Request request;
34     char *server_name;
35
36     FCGX_InitRequest(&request, 0, 0);
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         /* Some platforms require accept() serialization, some don't.. */
44         pthread_mutex_lock(&accept_mutex);
45         rc = FCGX_Accept_r(&request);
46         pthread_mutex_unlock(&accept_mutex);
47
48         if (rc < 0)
49             break;
50
51         server_name = FCGX_GetParam("SERVER_NAME", request.envp);
52
53         FCGX_FPrintF(request.out,
54             "Content-type: text/html\r\n"
55             "\r\n"
56             "<title>FastCGI Hello! (multi-threaded C, fcgiapp library)</title>"
57             "<h1>FastCGI Hello! (multi-threaded C, fcgiapp library)</h1>"
58             "Thread %d, Process %ld<p>"
59             "Request counts for %d threads running on host <i>%s</i><p><code>",
60             thread_id, pid, THREAD_COUNT, server_name ? server_name : "?");
61
62         sleep(2);
63
64         pthread_mutex_lock(&counts_mutex);
65         ++counts[thread_id];
66         for (i = 0; i < THREAD_COUNT; i++)
67             FCGX_FPrintF(request.out, "%5d " , counts[i]);
68         pthread_mutex_unlock(&counts_mutex);
69
70         FCGX_Finish_r(&request);
71     }
72
73     return NULL;
74 }
75
76 int main(void)
77 {
78     int i;
79     pthread_t id[THREAD_COUNT];
80
81     FCGX_Init();
82
83     for (i = 1; i < THREAD_COUNT; i++)
84         pthread_create(&id[i], NULL, doit, (void*)i);
85
86     doit(0);
87
88     exit(0);
89 }
90