/*
============================================================================
Name : timewait.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
//#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
static pthread_t thread;
static pthread_cond_t cond;
static pthread_mutex_t mutex;
static int flag = 0;
void * thr_fn(void * arg)
{
struct timeval now;
struct timespec outtime;
pthread_mutex_lock(&mutex);
int i=0;
while (flag) {
printf("*****:%d \n",i++);
gettimeofday(&now, NULL);
outtime.tv_sec = now.tv_sec + 5;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mutex, &outtime);
// pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
printf("cond thread exit\n");
}
int main(void) {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
flag=1;
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
printf("error when create pthread\n");
return 1;
}
char c ;
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\n");
//pthread_mutex_lock(&mutex);
flag = 0;
// pthread_cond_signal(&cond);
// pthread_mutex_unlock(&mutex);
printf("Wait for thread to exit\n");
pthread_join(thread, NULL);
printf("Bye\n");
// return 0;
//puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
return EXIT_SUCCESS;
}
linux pthread 多线程控制示例代码
需积分: 13 83 浏览量
2015-01-08
11:20:26
上传
评论
收藏 64KB GZ 举报
随风而去飘飘飘
- 粉丝: 617
- 资源: 45
最新资源
- Python大作业:音乐播放软件(爬虫+可视化+数据分析+数据库)
- 课程设计-python爬虫-爬取日报,爬取日报文章后存储到本地,附带源代码+课程设计报告
- 软件和信息技术服务行业投资与前景预测.pptx
- 课程设计-基于SpringBoot + Mybatis+python爬虫NBA球员数据爬取可视化+源代码+文档+sql+效果图
- 软件品质管理系列二项目策划规范.doc
- 基于TensorFlow+PyQt+GUI的酒店评论情感分析,支持分析本地数据文件和网络爬取数据分析+源代码+文档说明+安装教程
- 软件定义无线电中的模拟电路测试技术.pptx
- 软件开发协议(作为技术开发合同附件).doc
- 软件开发和咨询行业技术趋势分析.pptx
- 软件测试题详解及答案.doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈