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; 
    }

     运行结果:

  • 相关阅读:
    洪小瑶学iOS-UINavigationController
    flash模拟苹果菜单原理
    洪小瑶学iOS-NSNotificationCenter 详解
    关于体感互动Airkinect研究《案例篇1》
    AS3 兩點求距離
    右鍵點擊Right Click (Flash Player 11.2 新功能)
    像素级碰撞检测研究
    关于体感互动kinect研究《基础篇》
    部署Pentaho BI服务器到独立Tomcat所碰到的问题总结
    c语言的一个技巧问题
  • 原文地址:https://www.cnblogs.com/nanqiang/p/11438722.html
Copyright © 2011-2022 走看看