0%

Linux信号量Semaphore进程间同步

Semaphone 信号量多进程同步

  • 可以使用 POSIX 信号量(semaphore)来进行进程间的同步
  • #include <semaphore.h>
  • 然后可以在使用fork()创建新的进程的时候,使用semaphone控制进程同步,两个进程可以利用semaphore互相控制
  • 主要的api是
    • int sem_init(sem_t *sem, int pshared, unsigned int value);创建
    • int sem_destroy(sem_t *sem);销毁
    • int sem_wait(sem_t *sem);阻塞等待
    • int sem_trywait(sem_t *sem);尝试等待,不阻塞
    • int sem_post(sem_t *sem);释放
    • int sem_getvalue(sem_t *sem, int *sval);获取信号量的值
      #include <iostream>
      #include <semaphore.h>
      #include <unistd.h>
      #include <sys/wait.h>

      int main() {
      // 创建信号量
      sem_t mySemaphore;
      sem_init(&mySemaphore, 1, 1); // 参数 1 表示信号量在进程间共享,初始值为 1

      // 创建子进程
      pid_t childPid = fork();

      if (childPid == -1) {
      // 错误处理
      std::cerr << "Fork failed." << std::endl;
      return 1;
      } else if (childPid == 0) {
      // 子进程
      sem_wait(&mySemaphore); // 等待信号量
      std::cout << "Child process is executing." << std::endl;
      sleep(2);
      sem_post(&mySemaphore); // 释放信号量
      } else {
      // 父进程
      sem_wait(&mySemaphore); // 等待信号量
      std::cout << "Parent process is executing." << std::endl;
      sem_post(&mySemaphore); // 释放信号量

      // 等待子进程结束
      wait(nullptr);
      }

      // 销毁信号量
      sem_destroy(&mySemaphore);

      return 0;
      }
  • 也可以在不同的线程之间用于同步
    #include <iostream>
    #include <thread>
    #include <semaphore.h>

    // 全局信号量
    sem_t mySemaphore;

    void threadFunction(int threadId) {
    // 在线程内等待信号量
    sem_wait(&mySemaphore);

    // 临界区代码
    std::cout << "Thread " << threadId << " is in the critical section." << std::endl;

    // 离开临界区后释放信号量
    sem_post(&mySemaphore);
    }

    int main() {
    // 初始化信号量
    sem_init(&mySemaphore, 0, 1); // 在线程间共享,初始值为 1

    // 创建两个线程
    std::thread t1(threadFunction, 1);
    std::thread t2(threadFunction, 2);

    // 等待线程结束
    t1.join();
    t2.join();

    // 销毁信号量
    sem_destroy(&mySemaphore);

    return 0;
    }