当前位置: 编程技术>c/c++/嵌入式
基于C++实现的线程休眠代码
来源: 互联网 发布时间:2014-10-29
本文导语: 本文实例讲述了基于C++实现的线程休眠代码,分享给大家供大家参考。具体方法如下: linux平台示例如下: /* File : thread1.c Author : Mike E-Mail : Mike_Zhang@live.com */ #include #include #include void m_threadSleep(int sec,int nsec) { st...
本文实例讲述了基于C++实现的线程休眠代码,分享给大家供大家参考。具体方法如下:
linux平台示例如下:
/* File : thread1.c Author : Mike E-Mail : Mike_Zhang@live.com */ #include #include #include 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 ...rn"); } void test2() { m_threadSleep(2,0); printf("I'm thread2 ...rn"); } 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("%drn",tend-tbegin); return 0; }
编译代码如下:
gcc thread1.c -o thread1 -lpthread
boost库实现示例如下:
/* File : boost_thread1.cpp Author : Mike E-Mail : Mike_Zhang@live.com */ #include #include #include 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
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
站内导航:
特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!