C++ based on the implementation of thread sleep code

  • 2020-04-02 02:46:27
  • OfStack

In this paper, the example of C++ based on the implementation of thread sleep code, to share for your reference. Specific methods are as follows:

The Linux platform example is as follows:



#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 ...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;
}

The compiled code is as follows:


gcc thread1.c -o thread1 -lpthread

An example of the boost library implementation is as follows:



#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;
}

Compile the command as follows:


g++ boost_thread1.cpp -o boost_thread1 -lboost_thread-mt

Hope that the article described in the C++ programming to help you.


Related articles: