linux的信号量实用例子sem_timedwait

//Linux 信号量的简单实用

#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h>
#include <pthread.h>
//int sem_init(sem_t *sem, int pshared, unsigned int value);
//int sem_destroy(sem_t *sem);
//int sem_wait(sem_t *sem);
//int sem_trywait(sem_t *sem);
//int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
sem_t sem;
    
void *func1(void *arg)
{
    struct timespec t1;
    struct timeval time1;
    gettimeofday(&time1, NULL);
    t1.tv_sec = time1.tv_sec+6; 
    int *running = (int *)arg;
    printf("thread func1 running : %d\n", *running);
    while(1){
        printf("thread func1 running.......11111\n");
        //sem_wait(&sem);
        //sem_trywait(&sem);
        sem_timedwait(&sem, &t1);
        printf("thread func1 running.......22222\n");
        //sleep(2);
        gettimeofday(&time1, NULL);
        t1.tv_sec = time1.tv_sec+6; 
        sem_post(&sem);
        printf("thread func1 running.......post\n");
        sleep(1);
    }
    pthread_exit(NULL);
}
    
void *func2(void *arg)//ui
{
    struct timespec t2;
    struct timeval time2;
    gettimeofday(&time2, NULL);
    t2.tv_sec = time2.tv_sec+3; 
    int *running = (int *)arg;
    printf("thread func2 running : %d\n", *running);
    while(1){
        printf("thread func2 running.......33333\n");
        //sem_wait(&sem);
        //sem_trywait(&sem);
        sem_timedwait(&sem, &t2);
        printf("thread func2 running.......44444\n");
        gettimeofday(&time2, NULL);
        t2.tv_sec = time2.tv_sec+3; 
        //sem_post(&sem);
        sleep(1);
    }
    pthread_exit(NULL);
}
    
int main(void)
{
    int a = 1;
    sem_init(&sem, 0, 1);
    pthread_t thread_id[2];
    
    pthread_create(&thread_id[0], NULL, func1, (void *)&a);
    //sleep(10);
    a = 2;
    pthread_create(&thread_id[1], NULL, func2, (void *)&a);
    printf("main thread running.\n");
    pthread_join(thread_id[0], NULL);
    pthread_join(thread_id[1], NULL);
    sem_destroy(&sem);
    
    return 0;
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值