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()函数输出
}
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;
}