linux sem信号量使用

时间:2022-08-29 15:16:35

Linux下关于信号量结构体表示为:sem_t

      操作结构体的函数:

      初始化函数: sem_init(sem_t * __sem,int __pshared,unsigned int __value);

      触发信号量值:sem_post(sem_t * __sem);

      等待信号量触发:

      通常有:

      一直等待:sem_wait(sem_t * __sem);  

      测试__sem是否触发:sem_trywait(sem_t * __sem); 

      等待超时:sem_timedwait(sem_t * __restrict __sem, __ const struct timespec * __restrict __abstime);

      释放销毁信号量:

      sem _destroy(sem_t * __sem);


例子:

(关于主进程等待线程问题,仍有疑问,但是可以用join实现,也可以设置变量来判断,这边暂时使用sleep,治标不治本,等待巧妙的方法来实现进程等多线程问题)

#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "semaphore.h"
#include "sys/time.h"
#include "assert.h"
#include "errno.h"
#include "signal.h"
#include "pthread.h"
#include "time.h"


void* thread1(void*);
void* thread2(void*);
void* thread3(void*);


int alex=0;
sem_t sem12;
sem_t sem13;


int main()
{
    pthread_t pid1,pid2,pid3;
    printf("--enter main:\n");
    int ret=sem_init(&sem12,0,0);
    if(ret!=0)
    {
      printf("sem12 init Fail\n");
      return ret;
    }
    ret=sem_init(&sem13,0,0);
    if(ret!=0)
    {
      printf("sem13 init Fail\n");
      return ret;
    }
    pthread_create(&pid1,NULL,thread1,NULL);
    pthread_create(&pid1,NULL,thread2,NULL);
    pthread_create(&pid1,NULL,thread3,NULL);
    sleep(6);
    sem_destroy(&sem12);
    sem_destroy(&sem13);
    printf("--end:\n");
    exit(0);
}




void* thread1(void* arg)
{
    printf("this is thread1:\n");
    int input;
    printf("put an number: \n");
    scanf("%d",&input);
    printf("the number is: %d\n",input);
    //sleep(2);
    sem_post(&sem12);
    sem_post(&sem13);
    printf("leave thread1\n");
    pthread_exit(0);
}




void* thread2(void* arg)
{
    printf("this is thread2:\n");
    sem_wait(&sem12);
    printf("leave thread2\n");
    pthread_exit(0);
}




void* thread3(void* arg)
{
    struct timespec ts;
    printf("this is thread3:\n");
    ts.tv_sec=time(NULL)+5;
    int s=sem_timedwait(&sem13,&ts);
    if(s==-1)
      printf("thread wait timeout\n");
    printf("leave thread3\n");
    pthread_exit(0);
}