理解
以前多线程只能用系统的API,无法解决跨平台问题,一套代码进行平台移植,对应多线程也必须要修改。C++11中只需要使用语言层面的thread可以解决这个问题。
参考:包含在#include< thread >
单个cpu内核的多个线程:一个时间片运行一个线程的代码,并不是真正意义的并行计算。
多个cpu或者多个内核:可以做到真正的并行计算
简单体验
下面的测试我在QT上面测试的,不知道为什么不能在网页上面进行
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
using namespace std;
void thread_1()
{
cout<<"thread_1"<<endl;
}
void thread_2(int x)
{
cout<<"x:"<<x<<endl;
cout<<"thread_2"<<endl;
}
int main()
{
thread first ( thread_1); // spawn new thread that calls thread_1() 开启线程,并调用thread_1
thread second (thread_2,100); // spawn new thread that calls thread_2(100)开启线程,并调用thread_2(100)
std::cout << "主线程\n";
// synchronize threads:
first.join(); // pauses until first finishes 这个操作完了之后才能destroyed
second.join(); // pauses until second finishes//join完了之后,才能往下执行。
std::cout << "thread_1&thread_2线程结束.\n";//必须join完成
return 0;
}
获取线程id
(thread::id & this_thread::get::get_id())
// thread::get_id / this_thread::get_id
#include <iostream> // std::cout
#include <thread> // std::thread, std::thread::id, std::this_thread::get_id
#include <chrono> // std::chrono::seconds
std::thread::id main_thread_id = std::this_thread::get_id();
void is_main_thread() {
if ( main_thread_id == std::this_thread::get_id() )
std::cout << "This is the main thread.\n";
else
std::cout << "This is not the main thread.\n";
}
int main()
{
is_main_thread();//普通函数调用
std::thread th (is_main_thread);//子线程调用
//或者可以用"="进行赋值
//std::thread th;
//th = std::thread(is_main_thread);
th.join();
}
detach
不需要join,可以直接destroyed
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning and detaching 3 threads...\n";
std::thread (pause_thread,1).detach();
std::thread (pause_thread,2).detach();
std::thread (pause_thread,3).detach();
std::cout << "Done spawning threads.\n";
std::cout << "(the main thread will now pause for 5 seconds)\n";
// give the detached threads time to finish (but not guaranteed!):
pause_thread(5);
return 0;
}
joinable
可以使用这个参数查看是否可以join
// example for thread::joinable
#include <iostream> // std::cout
#include <thread> // std::thread
void mythread()
{
// do stuff...
}
int main()
{
std::thread foo;
std::thread bar(mythread);
std::cout << "Joinable after construction:\n" << std::boolalpha;
std::cout << "foo: " << foo.joinable() << '\n';
std::cout << "bar: " << bar.joinable() << '\n';
if (foo.joinable()) foo.join();
if (bar.joinable()) bar.join();
std::cout << "Joinable after joining:\n" << std::boolalpha;
std::cout << "foo: " << foo.joinable() << '\n';
std::cout << "bar: " << bar.joinable() << '\n';
return 0;
}
运行结果:
Joinable after construction:
foo: false
bar: true
Joinable after joining:
foo: false
bar: false