欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

基于C++实现的线程休眠代码

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

本文实例讲述了基于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

希望本文所述对大家的C++程序设计有所帮助。

上一篇:C++ COM编程之接口背后的虚函数表

栏    目:C语言

下一篇:C++ COM编程之什么是组件?

本文标题:基于C++实现的线程休眠代码

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/3314.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有