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

#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include 
#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;
}


你可能感兴趣的:(linux)