在 Linux 下,C++ 可以使用信號量(semaphore)來實現進程間或線程間的同步。信號量是一種計數器,用于控制多個進程或線程對共享資源的訪問。在 Linux 中,信號量的實現主要依賴于 System V 信號量 API 或 POSIX 信號量 API。
以下是使用 POSIX 信號量 API 的一個簡單示例:
首先,確保你的系統支持 POSIX 信號量。你可以使用 man 7 sem
命令查看相關文檔。
創建一個名為 semaphore_example.cpp
的文件,并添加以下代碼:
#include <iostream>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
// 定義一個全局信號量
sem_t semaphore;
// 線程函數
void* thread_function(void* arg) {
// 等待信號量
sem_wait(&semaphore);
std::cout << "線程 " << pthread_self() << " 獲得了信號量" << std::endl;
sleep(1); // 模擬對共享資源的訪問
std::cout << "線程 " << pthread_self() << " 釋放了信號量" << std::endl;
// 釋放信號量
sem_post(&semaphore);
return nullptr;
}
int main() {
// 初始化信號量,初始值為 1(表示資源可用)
sem_init(&semaphore, 0, 1);
// 創建兩個線程
pthread_t thread1, thread2;
pthread_create(&thread1, nullptr, thread_function, nullptr);
pthread_create(&thread2, nullptr, thread_function, nullptr);
// 等待線程結束
pthread_join(thread1, nullptr);
pthread_join(thread2, nullptr);
// 銷毀信號量
sem_destroy(&semaphore);
return 0;
}
g++ -o semaphore_example semaphore_example.cpp -pthread
./semaphore_example
這個示例中,我們創建了一個全局信號量,并初始化為 1。這意味著資源一開始是可用的。我們創建了兩個線程,它們都嘗試獲取信號量。當一個線程獲得信號量時,另一個線程將被阻塞,直到信號量被釋放。這樣可以確保在任何時候只有一個線程訪問共享資源。
注意:在實際應用中,你需要根據具體需求調整信號量的初始值和使用方式。