本文实例讲述了基于C++实现的线程休眠代码,分享给大家供大家参考。具体方法如下:
linux平台示例如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/*
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;
}
|
编译代码如下:
?
1
|
gcc thread1.c -o thread1 -lpthread
|
boost库实现示例如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/*
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;
}
|
编译命令如下:
?
1
|
g++ boost_thread1.cpp -o boost_thread1 -lboost_thread-mt
|
希望本文所述对大家的C++程序设计有所帮助。
相关文章
猜你喜欢
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 60
-
2025-05-27 34
-
2025-05-29 84
-
2025-05-29 67
-
2025-06-04 13
热门评论