繼續C++11的std::thread之旅!
下面討論如何**給線程傳遞參數**?
這個例子是傳遞一個string
~~~
#include <iostream>
#include <thread>
#include <string>
void thread_function(std::string s)
{
std::cout << "thread function ";
std::cout << "message is = " << s << std::endl;
}
int main()
{
std::string s = "Kathy Perry";
std::thread t(&thread_function, s);
std::cout << "main thread message = " << s << std::endl;
t.join();
return 0;
}
~~~
如果運行,我們可以從輸出結果看出傳遞成功了。
良好編程習慣的人都知道 傳遞引用的效率更高,那么我們該如何做呢??
你也許會這樣寫:
~~~
void thread_function(std::string &s)
{
std::cout << "thread function ";
std::cout << "message is = " << s << std::endl;
s = "Justin Beaver";
}
~~~
為了確認是否傳遞了引用?我們在線程函數后更改這個參數,但是我們可以看到,輸出結果并沒有變化,即不是傳遞的引用。
事實上, 依然是按值傳遞而不是引用。為了達到目的,我們可以這么做:
~~~
std::thread t(&thread_function, std::ref(s));
~~~
這不是唯一的方法:
我們可以使用move():
~~~
std::thread t(&thread_function, std::move(s));
~~~
接下來呢,我們就要將一下線程的復制吧!!?
以下代碼編譯通過不了:
~~~
#include <iostream>
#include <thread>
void thread_function()
{
std::cout << "thread function\n";
}
int main()
{
std::thread t(&thread_function);
std::cout << "main thread\n";
std::thread t2 = t;
t2.join();
return 0;
}
~~~
但是別著急,稍稍修改:
~~~
include <iostream>
#include <thread>
void thread_function()
{
std::cout << "thread function\n";
}
int main()
{
std::thread t(&thread_function);
std::cout << "main thread\n";
std::thread t2 = move(t);
t2.join();
return 0;
}
~~~
大功告成!!!
再聊一個成員函數吧?**std::thread::get_id()**;
~~~
int main()
{
std::string s = "Kathy Perry";
std::thread t(&thread_function, std::move(s));
std::cout << "main thread message = " << s << std::endl;
std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
std::cout << "child thread id = " << t.get_id() << std::endl;
t.join();
return 0;
}
Output:
thread function message is = Kathy Perry
main thread message =
main thread id = 1208
child thread id = 5224
~~~
聊一聊**std::thread::hardware_concurrency()**?
獲得當前多少個線程:
~~~
int main()
{
std::cout << "Number of threads = "
<< std::thread::hardware_concurrency() << std::endl;
return 0;
}
//輸出:
Number of threads = 2
~~~
之前介紹過c++11的**lambda表達式**?
我們可以這樣使用:
~~~
int main()
{
std::thread t([]()
{
std::cout << "thread function\n";
}
);
std::cout << "main thread\n";
t.join(); // main thread waits for t to finish
return 0;
}
~~~
- 前言
- 吐血整理C++11新特性
- C++11新特性之std::function
- c++11特性之正則表達式
- c++11特性之Lambda表達式
- c++11特性之override和final關鍵字
- c++11特性之std::thread--初識
- c++11特性之std::thread--初識二
- c++11特性之initializer_list
- c++11特性之std::thread--進階
- c++11特性之std::thread--進階二
- C++11新特性之 CALLBACKS
- C++11新特性之 std::array container
- C++11新特性之 nullptr
- C++11新特性之 rvalue Reference(右值引用)
- C++11新特性之 Move semantics(移動語義)
- C++11新特性之 default and delete specifiers
- C++11新特性之 Static assertions 和constructor delegation
- 開始使用C++11的幾個理由
- C++11新特性之 std::future and std::async