下面是一个使用信号量(semaphore)实现非亲缘关系进程间同步的例子:

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>

sem_t sem;

void* thread_func(void* arg) {
    int* thread_id = (int*)arg;

    // 线程等待信号量
    sem_wait(&sem);

    printf('Thread %d is running\n', *thread_id);

    // 线程执行完毕后释放信号量
    sem_post(&sem);

    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    int thread_id1 = 1, thread_id2 = 2;

    // 初始化信号量
    sem_init(&sem, 0, 1);

    // 创建线程1
    if (pthread_create(&thread1, NULL, thread_func, &thread_id1) != 0) {
        perror('pthread_create failed');
        exit(EXIT_FAILURE);
    }

    // 创建线程2
    if (pthread_create(&thread2, NULL, thread_func, &thread_id2) != 0) {
        perror('pthread_create failed');
        exit(EXIT_FAILURE);
    }

    // 等待线程1和线程2执行完毕
    if (pthread_join(thread1, NULL) != 0) {
        perror('pthread_join failed');
        exit(EXIT_FAILURE);
    }

    if (pthread_join(thread2, NULL) != 0) {
        perror('pthread_join failed');
        exit(EXIT_FAILURE);
    }

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

    return 0;
}

在上面的例子中,我们使用了一个信号量来实现线程间的同步。线程1和线程2都会等待信号量,一旦获取到信号量就会输出自己的线程ID,并释放信号量,让其他线程获得机会执行。由于信号量的值为1,所以只有一个线程能够获取到信号量,另一个线程必须等待。通过这种方式,我们实现了线程间的同步。

Linux 进程间同步:Semaphore 实例与 C 代码

原文地址: https://www.cveoy.top/t/topic/nD7O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录