commit 451d964

default  ·  2023-02-06 17:59:20 +0000 UTC
parent 06fc40e
More thread work.
1 files changed,  +47, -8
+47, -8
 1@@ -335,14 +335,16 @@ xs_list *job_fifo = NULL;
 2 void job_post(const xs_val *job)
 3 /* posts a job for the threads to process it */
 4 {
 5-    /* lock the mutex */
 6-    pthread_mutex_lock(&job_mutex);
 7+    if (job != NULL) {
 8+        /* lock the mutex */
 9+        pthread_mutex_lock(&job_mutex);
10 
11-    /* add to the fifo */
12-    job_fifo = xs_list_append(job_fifo, job);
13+        /* add to the fifo */
14+        job_fifo = xs_list_append(job_fifo, job);
15 
16-    /* unlock the mutex */
17-    pthread_mutex_unlock(&job_mutex);
18+        /* unlock the mutex */
19+        pthread_mutex_unlock(&job_mutex);
20+    }
21 
22     /* ask for someone to attend it */
23     sem_post(&job_sem);
24@@ -371,6 +373,33 @@ void job_wait(xs_val **job)
25 #define MAX_THREADS 256
26 #endif
27 
28+static void *job_thread(void *arg)
29+/* job thread */
30+{
31+//    httpd_connection((FILE *)arg);
32+    srv_debug(0, xs_fmt("job thread started"));
33+
34+    for (;;) {
35+        xs *job = NULL;
36+
37+        job_wait(&job);
38+
39+        srv_debug(0, xs_fmt("job thread wake up"));
40+
41+        if (job == NULL)
42+            break;
43+
44+        if (xs_type(job) == XSTYPE_DATA) {
45+            /* it's a socket */
46+        }
47+    }
48+
49+    srv_debug(0, xs_fmt("job thread stopped"));
50+
51+    return NULL;
52+}
53+
54+
55 void httpd(void)
56 /* starts the server */
57 {
58@@ -379,6 +408,7 @@ void httpd(void)
59     int rs;
60     pthread_t threads[MAX_THREADS];
61     int n_threads = 0;
62+    int n;
63 
64     address = xs_dict_get(srv_config, "address");
65     port    = xs_number_get(xs_dict_get(srv_config, "port"));
66@@ -417,6 +447,10 @@ void httpd(void)
67     /* thread #0 is the background thread */
68     pthread_create(&threads[0], NULL, background_thread, NULL);
69 
70+    /* the rest of threads are for job processing */
71+    for (n = 1; n < n_threads; n++)
72+        pthread_create(&threads[n], NULL, job_thread, NULL);
73+
74     if (setjmp(on_break) == 0) {
75         for (;;) {
76             FILE *f = xs_socket_accept(rs);
77@@ -430,8 +464,13 @@ void httpd(void)
78 
79     srv_running = 0;
80 
81-    /* wait for the background thread to end */
82-    pthread_join(threads[0], NULL);
83+    /* send as many empty jobs as working threads */
84+    for (n = 1; n < n_threads; n++)
85+        job_post(NULL);
86+
87+    /* wait for all the threads to exit */
88+    for (n = 0; n < n_threads; n++)
89+        pthread_join(threads[n], NULL);
90 
91     job_fifo = xs_free(job_fifo);
92