线程睡眠、互斥锁条件变量、time

1 sleep 支持线程
2 usleep 支持线程
3 锁跟信号量 方法

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>



#include<time.h> //C语言的头文件   

  
void mytime()  
{   
time_t now; //实例化time_t结构    
struct tm *timenow; //实例化tm结构指针    
time(&now);   
//time函数读取现在的时间(国际标准时间非北京时间),然后传值给now    
  
timenow = localtime(&now);   
//localtime函数把从time取得的时间now换算成你电脑中的时间(就是你设置的地区)    
  
printf("Local time is %s/n",asctime(timenow));   
//上句中asctime函数把时间转换成字符,通过printf()函数输出  
printf("%d\n%d\n%d\n%d\n%d\n%d\n",
timenow->tm_year+1900,timenow->tm_mon+1,timenow->tm_mday,timenow->tm_hour,
timenow->tm_min,timenow->tm_sec); //注意只有先执行了asctime,才会正确打印时间
}   



static pthread_t thread;   
static pthread_cond_t cond;       //条件变量
static pthread_mutex_t mutex;     //互斥锁
static int flag = 1;
 
void * thr_fn(void * arg) 
{
  struct timeval now;             //微秒              
  struct timespec outtime;        //纳秒
  pthread_mutex_lock(&mutex);     //获取锁
  
    printf("*****\n");
    gettimeofday(&now, NULL);     //获取  struct timeval类型的时间  
    outtime.tv_sec = now.tv_sec + 240;    //确定时间
    outtime.tv_nsec = now.tv_usec * 1000;   //赋值也是确定  时间
    mytime();
    pthread_cond_timedwait(&cond, &mutex, &outtime);   //第三个参数  等待时间(其值为系统时间 + 等待时间)
	
  
  pthread_mutex_unlock(&mutex);    //释放锁
  printf("cond thread exit\n");
  mytime();
}
 
int main(void) 
{
  pthread_mutex_init(&mutex, NULL);    //初始化互斥锁
  pthread_cond_init(&cond, NULL);      //初始化条件变量
  if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
    printf("error when create pthread,%d\n", errno);
    return 1;
  }
  char c ; 
  while ((c = getchar()) != 'q');
  printf("Now terminate the thread!\n");
 
  pthread_mutex_lock(&mutex);
  
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);
  printf("Wait for thread to exit\n");
  pthread_join(thread, NULL);
  printf("Bye\n");
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值