1-2. C++併發(線程傳參)

如何向線程內傳遞參數
案例1:想線程中傳遞參數

#include <thread>
void f(int i, std::string const& s);
std::thread t(f, 3, "hello");

案例2:線程拷貝參數變量或引用參數變量
想要引用參數,則需要使用std::ref來包裝參數,不然參數將會被複制到線程中,再進行引用

#include <thread>
void update_data_for_widget(widget_id w, widget_data& data);
void oops_again(widget_id w)
{
	widget_data data;
	std::thread t(update_data_for_widget, w, data);//線程會強制拷貝參數變量,若果想要引用則使用 std::thread t(update_data_for_widget, w, std::ref(data)
	display_status();
	t.join();
	process_widget_data(data);
}

案例3:可以傳遞一個成員函數指針作爲線程函數,並提供一個合適的對象指針作爲第一個參數,因爲成員函數的第一個參數默認爲對象指針(除了靜態成員函數)

#include <thread>
class X
{
public:
	void do_lengthy_work(int);
};
X my_x;
int num(0);
std::thread t(&X::do_lengthy_work, &my_x, num);//其中作爲參數的對象將會被轉移而不是拷貝,該處調用my_x.do_lengthy_work(num)

案例4:另外出現參數轉移的情況是結合unique_ptr的使用
該例子中,big_object的所有權先被轉移到新線程中,然後進行處理

#include <iostream>
#include <thread>
void process_big_object(std::unique_ptr<big_object>);
std::unique_ptr<big_object> p(new big_object);
p->prepare_data(42);
std::thread t(process_big_object, std::move(p));

*內容整理自《C++併發編程實戰》

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