在 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。这意味着资源一开始是可用的。我们创建了两个线程,它们都尝试获取信号量。当一个线程获得信号量时,另一个线程将被阻塞,直到信号量被释放。这样可以确保在任何时候只有一个线程访问共享资源。
注意:在实际应用中,你需要根据具体需求调整信号量的初始值和使用方式。