C
Process and thread
Write parallel processing with fork and pthread.
Process and thread
In this lesson you'll define the worker_init function. With pthread you start a thread and wait for it with pthread_join. The thread increments the worker_count variable under a mutex.
This is the parallelism layer of the project. pthread_create(&t, NULL, worker_fn, NULL) creates the thread; pthread_join(t, NULL) waits for it to finish. Inside worker_fn you lock the mutex, increment the counter, unlock. This pattern is the basis of a real server that spawns a thread per client.
worker_init body
The worker function void *worker_fn(void *arg) locks the mutex, does worker_count++, unlocks. We suppress the unused parameter warning with (void)arg;.
int worker_init(void): declare pthread_t t;, start the thread with pthread_create(&t, NULL, worker_fn, NULL), wait with pthread_join(t, NULL), return 1;. In main call worker_init(); and printf("sayaç: %d\n", worker_count);. Output: "Proje hazır" then "sayaç: 1". The main from the previous lesson is included in the starting code.
Exercise Add worker_init
Write void *worker_fn(void *arg): (void)arg;, pthread_mutex_lock(&worker_lock);, worker_count++;, pthread_mutex_unlock(&worker_lock);, return NULL;. Write int worker_init(void): pthread_t t;, pthread_create(&t, NULL, worker_fn, NULL);, pthread_join(t, NULL);, return 1;. Add worker_init(); and printf("sayaç: %d\n", worker_count); to main.
Show example solution
#include <stdio.h>
#include <pthread.h>
int worker_init(void);
int server_setup(void);
int ipc_setup(void);
int worker_count = 0;
pthread_mutex_t worker_lock = PTHREAD_MUTEX_INITIALIZER;
void *worker_fn(void *arg) {
(void)arg;
pthread_mutex_lock(&worker_lock);
worker_count++;
pthread_mutex_unlock(&worker_lock);
return NULL;
}
int worker_init(void) {
pthread_t t;
pthread_create(&t, NULL, worker_fn, NULL);
pthread_join(t, NULL);
return 1;
}
int main(void) {
printf("Proje hazır\n");
worker_init();
printf("sayaç: %d\n", worker_count);
return 0;
}
Test yourself
-
Match pthread concepts
- pthread_create
- Starts thread
- pthread_join
- Waits thread
- pthread_mutex_lock
- Takes lock
- worker_count
- Counter
-
What does pthread_join do?
- Creates a thread
- Kills a thread
- Suspends a thread
- Waits for a thread
Show answer
Waits for a thread — pthread_join waits until the thread finishes.
-
pthread_create call
pthread_create(&t, NULL, worker_fn, ____);
Show answer
pthread_create(&t, NULL, worker_fn, NULL);
Next lesson: Socket layer