把執行緒同步的基礎觀念弄懂,之後理解 Python 的 threading 會輕鬆很多。
兩個執行緒同時跑時,很難避免同時存取同一個變數或檔案,因此需要一組機制來保證正確性,最常見的兩種工具就是訊號量(semaphore)與互斥量(mutex)。
訊號量可分為最簡單的「二進位訊號量」與更通用的「計數訊號量」。前者通常用來保護一段程式碼,讓它每次只能被一個執行緒執行;後者則用於允許有限數量的執行緒同時進入。技術上計數訊號量是二進位訊號量的邏輯延伸,兩者呼叫的函式其實相同。
互斥量與訊號量非常相似,實際上彼此可以互相實作,但在某些情境下用其中一種語意更貼切、效果也更好。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
void *thread_function(void *arg);
sem_t bin_sem;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = sem_init(&bin_sem, 0, 0); /* 初始化訊號量,初始值 0 */
if (res != 0) {
perror("Semaphore initialization failed");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
printf("Input some text, Enter 'end' to finish\n");
while (strncmp("end", work_area, 3) != 0) {
fgets(work_area, WORK_SIZE, stdin);
sem_post(&bin_sem); /* 訊號量 +1 */
}
printf("\nWaiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined\n");
sem_destroy(&bin_sem);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
sem_wait(&bin_sem); /* 等待訊號量大於 0,然後 -1 */
while (strncmp("end", work_area, 3) != 0) {
printf("You input %ld characters\n", strlen(work_area) - 1);
sem_wait(&bin_sem);
}
pthread_exit(NULL);
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, NULL);
if (res != 0) {
perror("Mutex initialization failed");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
pthread_mutex_lock(&work_mutex);
printf("Input some text, Enter 'end' to finish\n");
while (!time_to_exit) {
fgets(work_area, WORK_SIZE, stdin);
pthread_mutex_unlock(&work_mutex);
while (1) {
pthread_mutex_lock(&work_mutex);
if (work_area[0] != '\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
} else {
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\nWaiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined\n");
pthread_mutex_destroy(&work_mutex);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
sleep(1);
pthread_mutex_lock(&work_mutex);
while (strncmp("end", work_area, 3) != 0) {
printf("You input %ld characters\n", strlen(work_area) - 1);
work_area[0] = '\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while (work_area[0] == '\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
兩段程式做的是同一件事:主執行緒負責讀輸入,子執行緒負責回報字元數。訊號量版本靠 sem_post/sem_wait 傳遞「資料已備好」的訊號;互斥量版本則用鎖搭配一個空字串當作「有沒有新資料」的旗標。比較兩者,不難體會同步機制的選擇往往取決於你想表達的語意。