zoukankan      html  css  js  c++  java
  • linux 信号量

    https://www.jianshu.com/p/6e72ff770244

    无名信号量

    只适合用于一个进程的不同线程

    #include <time.h>
    #include <stdio.h>
    #include <errno.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <signal.h>
    #include <semaphore.h>
        
    sem_t sem;
        
    void *func1(void *arg)
    {
        sem_wait(&sem); //一直等待,直到有地方增加信号量,执行之后信号量减一
        int *running = (int *)arg;
        printf("thread func1 running : %d
    ", *running);
        
        pthread_exit(NULL);
    }
        
    void *func2(void *arg)
    {
        printf("thread func2 running.
    ");
        sem_post(&sem);//增加信号量,加一
        
        pthread_exit(NULL);
    }
        
    int main(void)
    {
        int a = 3;
        sem_init(&sem, 0, 0);//初始化信号量
        pthread_t thread_id[2];
        
        pthread_create(&thread_id[0], NULL, func1, (void *)&a);
        printf("main thread running.
    ");
        sleep(5);
        pthread_create(&thread_id[1], NULL, func2, (void *)&a);
        printf("main thread still running.
    ");
        pthread_join(thread_id[0], NULL);
        pthread_join(thread_id[1], NULL);
        sem_destroy(&sem);//销毁信号量
        
        return 0;
    }

     运行结果如下:

    线程1虽然先创建,但是要一直等待,直到线程2增加信号量,线程1才能继续执行

    命名信号量,可以用于不同进程

    #include <time.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <signal.h>
    #include <semaphore.h>
        
    #define SEM_NAME "/sem_name"  //信号量的路径
        
    sem_t *p_sem;
        
    void *testThread(void *ptr)
    {
        sem_wait(p_sem);//信号量减一,信号量为0时阻塞
        pthread_exit(NULL);
    }
        
    int main(void)
    {
        int i = 0;
        pthread_t pid;
        int sem_val = 0;
        p_sem = sem_open(SEM_NAME, O_CREAT, 0555, 5);//初始化信号量为5
        
        if(p_sem == NULL)
        {
            printf("sem_open %s failed!
    ", SEM_NAME);
            sem_unlink(SEM_NAME);//解除关联
            return -1;
        }
        
        for(i = 0; i < 7; i++)
        {
            pthread_create(&pid, NULL, testThread, NULL);
            sleep(1);//等待子线程执行完毕
            pthread_join(pid, NULL);  //信号量为0之后,子线程将会阻塞,这里也阻塞
            sem_getvalue(p_sem, &sem_val);
            printf("semaphore value : %d
    ", sem_val);
        }
        
        sem_close(p_sem);//关闭
        sem_unlink(SEM_NAME);//解除关联
      return 0; 
    }

     运行结果:

  • 相关阅读:
    IIS7.5 webapi 不支持 Delete、Put 解决方法
    pip 安装 MySQL-python 失败
    Windows 下针对python脚本做一个简单的进程保护
    Python 多线程 Condition 的使用
    Python 无限循环
    Window nginx+tomcat+https部署方案 支持ios9
    Window Redis分布式部署方案 java
    Struts2注解 特别注意
    PermGen space Eclipse 终极解决方案
    特别备注一下一个缓存加载的问题,百度上还搜不出来,在一个老外的网站上看到的
  • 原文地址:https://www.cnblogs.com/nanqiang/p/11438722.html
Copyright © 2011-2022 走看看