zoukankan      html  css  js  c++  java
  • 进程间通信之 信号量

    定义:信号量是一个计数器,用于多进程对共享数据对象的存取访问控制。为了获得共享资源,进程需要执行下列操作

    信号量使用步骤:

    1:初始化信号量---->int sem_init(sem_t *sem, int pshared, unsigned int value);

    2:申请资源,并对信号量做减一操作----->int sem_wait(sem_t *sem);

    3:释放资源,并对信号量做加一操作------>int sem_post(sem_t *sem);

     测试程序

    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <sys/ipc.h>
    #include <sys/sem.h>
    #include <stdio.h>
    #include <pthread.h>
    #include <semaphore.h>

    int num = 0;

    void *func1(void *sem)
    {
        int sval;
        srand((unsigned)time(0));
        while(1)
        {
            int r = rand() % 3;
            sleep(r);
            if(0 == sem_wait(sem))
            {
                num++;
                printf("1 get it ");
            }
            sleep(r);
            printf("1 pass the ball ");
            sem_post(sem);
        }
    }

    void *func2(void *sem)
    {
        int sval;
        srand((unsigned)time(0));
        while(1)
        {
            int r = rand() % 3;
            sleep(r);
            if(0 == sem_wait(sem))
            {
                num++;
                printf("2 get it ");
            }
            sleep(r);
            printf("2 pass the ball ");
            sem_post(sem);
        }
    }

    void *func3(void *sem)
    {
        int sval;
        srand((unsigned)time(0));
        while(1)
        {
            int r = rand() % 3;
            sleep(r);
            if(0 == sem_wait(sem))
            {
                num++;
                printf("3 get it ");
            }
            sleep(r);
            printf("3 pass the ball ");
            sem_post(sem);
        }
    }

    int main()
    {
        sem_t sem;
        int pshared = 1;
        pthread_t tid;
        pthread_attr_t attr;       
        sem_init(&sem,pshared,1);
        if(0 != pthread_attr_init(&attr))
            perror("pthread_attr_init");
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);  //设置分离属性
        printf("start ");
        if(0 != pthread_create(&tid,&attr,func1,&sem))               
            perror("pthread_create");
        if(0 != pthread_create(&tid,&attr,func2,&sem))              
            perror("pthread_create");
        if(0 != pthread_create(&tid,&attr,func3,&sem))               
            perror("pthread_create");
        while(1)
        {
            if(30 == num)
            {
                break;
                printf("finshed ");
            }
        }
        return 0;
    }

  • 相关阅读:
    xfce4-windowck-plugin的替代品
    git使用Beyond Compare作为diff和merge工具
    Visual Studio设置多个快捷键
    scrapy参数-COOKIES_ENABLED 最权威解释, 帮你避坑
    Linux基础使用
    python 所有的库整理
    Nginx配置详解
    15个常用的javaScript正则表达式
    Redis开发建议
    mysql 同步大量数据小技巧
  • 原文地址:https://www.cnblogs.com/be-m/p/4270862.html
Copyright © 2011-2022 走看看