linux sem信號量使用

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章