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 ↩︎

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