基于C++實現(xiàn)的線程休眠代碼
更新時間:2014年10月08日 10:04:38 投稿:shichen2014
這篇文章主要介紹了基于C++實現(xiàn)的線程休眠代碼,包括了Linux平臺及基于boost庫的兩種實現(xiàn)方法,有不錯的參考借鑒價值,需要的朋友可以參考下
本文實例講述了基于C++實現(xiàn)的線程休眠代碼,分享給大家供大家參考。具體方法如下:
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庫實現(xiàn)示例如下:
/*
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
希望本文所述對大家的C++程序設計有所幫助。
相關文章
C++容器適配與棧的實現(xiàn)及dequeque和優(yōu)先級詳解
這篇文章主要介紹了C++容器適配與棧的實現(xiàn)及dequeque和優(yōu)先級,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-10-10

