This article describes the implementation of the C + + thread sleep code, shared for everyone to reference. The specific methods are as follows:
Examples of Linux platforms are as follows:
/*
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;
}
Compile the code as follows:
GCC Thread1.c-o thread1-lpthread
The Boost library Implementation example is as follows:
/*
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;
}
The compilation commands are as follows:
g++ Boost_thread1.cpp-o BOOST_THREAD1-LBOOST_THREAD-MT
I hope this article will help you with the C + + program design.