C++併發(線程傳參)

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

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

案例2:線程拷貝參數變量或引用參數變量

#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);//其中作爲參數的對象將會被轉移而不是拷貝
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章