信号灯实现父子线程间通信

本文介绍了一个使用信号灯(semaphore)机制实现线程间通信的例子。通过定义信号灯集和进行P/V操作来同步两个线程的行为。主函数创建了一个线程并对其进行P操作,该线程执行任务后进行V操作,演示了信号灯在线程同步中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include <unistd.h>
#include "semaphore.h"
#include"sys/ipc.h"
#include "sys/sem.h"
union semun {//初始化信号的值所用参数
               int              val;    /* Value for SETVAL */
               struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
               unsigned short  *array;  /* Array for GETALL, SETALL */
               struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                           (Linux-specific) */
           };
//定义一个信号灯集sem
int semid;
union semun mysemun;
struct sembuf mysembuf;
void * fun(void * var){
        //p操作
        mysembuf.sem_op=-1;
        semop(semid,&mysembuf,1);
        for(int i=0;i<10;i++){
                usleep(100);
                printf("this is fun j=%d\n",i);
        }
           };
//信号灯线程间通信
//定义一个信号灯集sem
int semid;
union semun mysemun;
struct sembuf mysembuf;
void * fun(void * var){
        //p操作
        mysembuf.sem_op=-1;
        semop(semid,&mysembuf,1);
        for(int i=0;i<10;i++){
                usleep(100);
                printf("this is fun j=%d\n",i);
        }
}
int main(){
        int i;
        char str[]="hello linux\n";
        pthread_t tid;
        int ret;
        semid=semget(IPC_PRIVATE,3,0777);
        if(semid<0){
                printf("create semaphore failure\n");
                return -1;
        }
        system("ipcs -s");
        mysemun.val=0;
        semctl(semid,0,SETVAL,mysemun);
        mysembuf.sem_num=0;
        mysembuf.sem_flg=0;
 ret=pthread_create(&tid,NULL,fun,(void *)str);
        if(ret<0){
                printf("create thread failure\n");
                return -1;
        }
        for(i=0;i<10;i++){
                usleep(100);
                printf("this is main fun i=%d\n",i);
        }
        //v操作
        mysembuf.sem_op=1;
        semop(semid,&mysembuf,1);
        while(1);
        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值