// CTest.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <thread>
#include <iostream>
void f1(int n)
{
for (int i = 0; i < 5; ++i)
{
std::cout << "Thread 1 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 1; ++i)
{
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f3()
{
for (int i = 0; i < 5; ++i)
{
std::cout << "Thread 3 executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n = 0;
std::thread t1;
std::thread t2(f1, n);<span style="white-space:pre"> </span>//傳參的構造函數
std::thread t3(f2, std::ref(n)); //傳引用的構造函數
std::thread t4(std::move(t3));<span style="white-space:pre"> </span>//將線程t3的所有者轉移給t4
std::thread t5(f3);<span style="white-space:pre"> </span>//不傳參的構造函數
std::cout << std::thread::hardware_concurrency() << std::endl;<span style="white-space:pre"> </span>//當前線程數
std::cout << t2.native_handle() << std::endl;<span style="white-space:pre"> </span>//當前線程的指針地址
std::cout << "Final value of n is " << n <<"\n";
std::cout << "before swap\n";
std::cout << "t2_id:" << t2.get_id() << "\n";
std::cout << "t4_id:" << t4.get_id() << "\n";
std::cout << "after swap \n";
std::swap(t2, t4);<span style="white-space:pre"> </span>//轉換t2 t4
std::cout << "t2_id:" << t2.get_id() << "\n";
std::cout << "t4_id:" << t4.get_id() << "\n";
<span style="white-space:pre"> </span><pre name="code" class="cpp"> t5.detach();<span style="white-space:pre"> </span>//獨立出線程t5
t2.join();
// 等待t2 線程結束 t4.join();
<span style="white-space:pre"> </span>
return 0;
}