c++11 thread跨平台使用的简单实例

thread创建:join与detach

std::thread是c++11新引入的线程标准库,通过其可以方便的编写与平台无关的多线程程序,虽然对比针对平台来定制化多线程库会使性能达到最大,但是会丧失了可移植性。

在使用std::thread的时候,对创建的线程有两种操作:等待/分离,也就是join/detach操作。join()操作是在std::thread t(func)后“某个”合适的地方调用,其作用是回收对应创建的线程的资源,避免造成资源的泄露。detach()操作是在std::thread t(func)后马上调用,用于把被创建的线程与做创建动作的线程分离,分离的线程变为后台线程,其后,创建的线程的“死活”就与其做创建动作的线程无关,它的资源会被init进程回收。1

#include <thread>
#include <stdio.h>

using namespace std;
void TestThread1();
void TestThread2();

int main() {

	thread t1(TestThread1);
	t1.join();
	thread t2(TestThread2);
	t2.detach();
	printf("这是主线程\n");
	getchar();

}

void TestThread1() {
	for (int i = 0; i < 10; i++) {

		printf("TestThread1:%d\n", i);
		std::this_thread::sleep_for(std::chrono::seconds(1));//休眠1s
	}
}
void TestThread2() {
	for (int i = 100; i < 110; i++) {

		printf("TestThread2:%d\n", i);
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

定时功能

C++11的chrono库定义了常用的时间间隔。2

std::this_thread::sleep_for(std::chrono::seconds(1)); //休眠一秒
std::this_thread::sleep_for(std::chrono:: milliseconds (1)); //休眠1毫秒

Linux编译c++11 cpp

示例demo存储为一个cpp文件c_thread.cpp,g++编译命令为如下截图。注意的地方是需要通过-std=c++11指定以c++11标准编译,并增加链接选项 -pthread。3
编译命令

运行结果

运行结果

参考文献


  1. https://www.cnblogs.com/liangjf/p/9801496.html ↩︎

  2. https://blog.csdn.net/oncealong/article/details/28599655 ↩︎

  3. https://www.iteye.com/blog/chaoslawful-568602 ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章