随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

线程休眠代码(C++)

linux平台示例:

复制代码
/*
File : thread1.c
Author : Mike
E-Mail : Mike_Zhang@live.com
*/
#include <stdio.h>
#include <pthread.h>
#include <time.h>
void m_threadSleep(int sec,int nsec)
{
struct timespec sleepTime;
struct timespec returnTime;
sleepTime.tv_sec = sec;
sleepTime.tv_nsec = nsec;
nanosleep(&sleepTime, &returnTime);
}
void test1()
{
m_threadSleep(1,0);
printf("I'm thread1 ...\r\n");
}
void test2()
{
m_threadSleep(2,0);
printf("I'm thread2 ...\r\n");
}
int main()
{
pthread_t thread1,thread2;
void *result;
time_t tbegin,tend;
tbegin = time(NULL);
pthread_create(&thread1,NULL,(void*)&test1,NULL);
pthread_create(&thread2,NULL,(void*)&test2,NULL);
pthread_join(thread1,&result);
pthread_join(thread2,&result);
tend = time(NULL);
printf("%d\r\n",tend-tbegin);
return 0;
}
复制代码

编译:
gcc thread1.c -o thread1 -lpthread

boost库实现示例:

复制代码
/*
File : boost_thread1.cpp
Author : Mike
E-Mail : Mike_Zhang@live.com
*/
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>

boost::xtime getSleepTime(int sec,int nsec)
{
boost::xtime t;
boost::xtime_get(&t, boost::TIME_UTC);
t.sec += sec;
t.nsec += nsec;
return t;
}
void test1()
{
boost::this_thread::sleep(getSleepTime(1,500));
std::cout <<"I'm thread1 !"<< std::endl;
}
void test2()
{
boost::this_thread::sleep(getSleepTime(3,500));
std::cout <<"I'm thread2 !"<< std::endl;
}

int main(int argc, char* argv[])
{
boost::thread thrd1(&test1);
boost::thread thrd2(&test2);
std::time_t t_begin,t_end;
t_begin = time(NULL);
thrd1.join();
thrd2.join();
t_end = time(NULL);
std::cout<<t_end-t_begin<<std::endl;
return 0;
}
复制代码

编译命令:
g++ boost_thread1.cpp -o boost_thread1 -lboost_thread-mt

posted on   Mike_Zhang  阅读(4414)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年1月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
5 6 7 8 9 10 11

点击右上角即可分享
微信分享提示