Cpp Concurrency In Action(读书笔记1)——线程入门及管理

10 篇文章 0 订阅
9 篇文章 0 订阅

前言:


本书译文:点击打开链接

本书原文:点击打开链接

原文纠错说明:点击打开链接

本书原文代码:左侧有下载处点击打开链接

读书笔记的代码都是在VS2015(Windows)下运行的。部分代码做了修改,如果改错了欢迎指出交流,水平不足,第一次读本书,觉得比较艰辛。另外:我删掉了部分作者代码中的”{}“,后来才发现,这是作者用来控制作用域的。代码不同之处,请参考原书源码。


线程入门

#include <iostream>
#include <thread> //1
void hello() //2
{
	std::cout << "Hello Concurrent World\n";
}
int main()
{
	std::thread t(hello); //3:新线程的初始函数,启动线程
	t.join(); //4:调用线程等待与t相关的线程
	system("pause");
	return 0;
}

启动线程

#include <iostream>
#include <thread>
void do_something()
{
	std::cout << "do_something()" << std::endl;
}
void do_something_else()
{
	std::cout << "do_something_else()" << std::endl;
}
class background_task
{
public:
	void operator()() const
	{
		do_something();
		do_something_else();
	}
};
void hello()
{
	std::cout << "Hello Concurrent World\n";
}
int main()
{
	std::thread t(hello); 
	t.join(); //等待完成,加入式
	//传入实例
	background_task f;
	std::thread my_thread1(f);
	my_thread1.join();

	//传入函数对象:该类的对象称作函数对象

	//std::thread my_thread(background_task());
	/*错误,声明了一个名为my_thread的函数,
	*这个函数带有一个参数(函数指针指向没有参数并返回background_task对象的函数),
	*返回一个 std::thread 对象的函数,而非启动了一个线程。
	*/

	std::thread my_thread2((background_task()));//多加一个括号
	my_thread2.join();

	std::thread my_thread3{ background_task() };//统一的初始化语法
	my_thread3.join();

	//传入lambda表达式
	std::thread my_thread4([] {
		do_something();
		do_something_else();
	});
//	my_thread4.join();//此处显示没有定义join(),待处理
	system("pause");
	return 0;
}

函数已经结束,线程依旧访问局部变量

#include <iostream>
#include <thread>
void do_something(unsigned i)
{
	std::cout << "do_something("<<i<<")" << std::endl;
}
struct func
{
	int& i;
	func(int& i_) : i(i_) {}
	void operator() ()
	{
		for (unsigned j = 0; j<1000000; ++j)
		{
			do_something(i); // 1. 潜在访问隐患:悬空引用
		}
	}
};
void oops()
{
	int some_local_state = 0;
	func my_func(some_local_state);
	std::thread my_thread(my_func);
	//my_thread.detach(); // 2. 不等待线程结束,这时输出的i值不确定
	my_thread.join();//如果使用这句,输出i=0
} // 3. 新线程可能还在运行
int main()
{
	oops();
	system("pause");
	return 0;
}
join()是简单粗暴的等待线程完成或不等待。当你需要对等待中的线程有更灵活的控制时,比如,看一下某个线程是否结束,或者只等待一段时间(超过时间就判定为超时)。想要做到这些,你需要使用其他机制来完成,比如条件变量和期待(futures),相关的讨论将会在第4章继续。调用join()的行为,还清理了线程相关的存储部分,这样 std::thread 对象将不再与已经完成的线程有任何关联。这意味着,只能对一个线程使用一次join();一旦已经使用过join(), std::thread 对象就不能再次加入了,当对其使用joinable()时,将返回否(false)。

等待线程完成

void f()
{
	int some_local_state = 0;
	func my_func(some_local_state);
	std::thread t(my_func);
	try
	{
		do_something_else();
	}
	catch (...)
	{
		t.join(); // 1
		throw;
	}
	t.join(); // 2
}

使用RAII等待线程完成

#include <iostream>
#include <thread>
void do_something(unsigned i)
{
	std::cout << "do_something("<<i<<")" << std::endl;
}
void do_something_else()
{

}
struct func
{
	int& i;
	func(int& i_) : i(i_) {}
	void operator() ()
	{
		for (unsigned j = 0; j<10; ++j)
		{
			do_something(i); // 1. 潜在访问隐患:悬空引用
		}
	}
};
class thread_guard
{
	std::thread& t;
public:
	//不错的构造函数编写格式
	explicit thread_guard(std::thread& t_) 
		:t(t_)
	{}
	~thread_guard()
	{
		if (t.joinable()) // 1
		{
			t.join(); // 2
		}
	}
	thread_guard(thread_guard const&) = delete; // 3
	thread_guard& operator=(thread_guard const&) = delete;
};
void f()
{
	int some_local_state = 0;
	func my_func(some_local_state);
	std::thread t(my_func);
	thread_guard g(t);//资源管理类来管理,RAII(资源获取即初始化方式)
	do_something_else();
} // 4
int main()
{
	f();
	system("pause");
	return 0;
}

后台运行线程

#include <iostream>
#include <thread>
#include <cassert>
void f()
{
	int some_local_state = 0;
	func my_func(some_local_state);
	std::thread t(my_func);
	t.detach();
	assert(!t.joinable());//不可再加入
	//预处理名字由预处理器管理,如果表达式为真则什么也不做!
} 

向线程函数传递参数

传递一个成员函数指针作为线程函数,并提供一个合适的对象指针作为第一个参数:
class X
{
public:
	void do_lengthy_work();
};
X my_x;
std::thread t(&X::do_lengthy_work, &my_x); // 1
新线程将my_x.do_lengthy_work()作为线程函数;my_x的地址①作为指针对象提供给函数。也可以为成员函数提供参数: std::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);
普通函数参数传递
#include <iostream>
#include <thread>
#include <string>
void f(int i, std::string const& s)
{
	std::cout  << i << "\t" <<s<< std::endl;
}
void oops(int some_param)
{
	char buffer[1024]; 
	sprintf_s(buffer, "%i", some_param);//%i=%d----%u
	std::thread t1(f, 2, buffer);
	//函数有很有可能会在字面值转化成 std::string 对象之前崩溃,从而导致一些未定义的行为。
	t1.join();
	std::thread t2(f, 3, std::string(buffer)); 
	/*想要依赖隐式转换将字面值转换为函数期待的 std::string 对象,
	*但因 std::thread 的构造函数会复制提供的变量,
	*就只复制了没有转换成期望类型的字符串字面值。
	*/
	t2.detach();
}
int main()
{
	std::thread t(f, 1, "hello");
	oops(512111);
	system("pause");
	return 0;
}

传递引用

#include <iostream>
#include <thread>
#include <string>
void f(const std::string &s,int &i)
{
	std::cout  << i <<s<< std::endl;
	++i;
}
int main()
{
	int a = 1;
//	std::thread t(f, "hello",a);
	/*错误,第二个参数期待传入一个引用,但是 std::thread 的构造函数并不知晓;
	*构造函数无视函数期待的参数类型,并盲目的拷贝已提供的变量。
	*当线程调用f函数时,传递给函数的参数是a变量内部拷贝的引用,而非数据本身的引用。
	*因此,当线程结束时,内部拷贝数据将会在数据更新阶段被销毁,
	*且后面的a将会是没有修改的变量。
	*/
	std::thread t(f,"hello",std::ref( a));
	t.join();
	f("world",a);
	std::cout << a << std::endl;
	system("pause");
	return 0;
}

std::move

#include <iostream>
#include <thread>
#include <memory>
class big_object {
public:
	void prepare_data(int _a)
	{
		a = _a;
	}
	int a;
};
void process_big_object(std::unique_ptr<big_object> p)
{
	std::cout << p->a << std::endl;
}
int main()
{
	std::unique_ptr<big_object> p(new big_object);
	p->prepare_data(42);
	std::thread t(process_big_object, std::move(p));//p无法拷贝,只能移动
	t.join();
	system("pause");
	return 0;
}
提供的参数可以"移动"(move),但不能"拷贝"(copy)。"移动"是指:原始对象中的数据转移给另一对象,而转移的这些数据就不再在原始对象中保存了(译者:比较像在文本编辑
的"剪切"操作)。 std::unique_ptr 就是这样一种类型。
当原对象是一个临时变量时,自动进行移动操作,但当原对象是一个命名变量,那么转移的时候就需要使用 std::move() 进行显示移动。

转移线程所有权

#include <iostream>
#include <thread>
void some_function(){}
void some_other_function(){}
int main()
{
	std::thread t1(some_function); // 1
	std::thread t2 = std::move(t1); // 2
	t1 = std::thread(some_other_function); // 3
	std::thread t3; // 4
	t3 = std::move(t2); // 5。t3:some_function;t1:some_other_function
	t1 = std::move(t3); // 6 赋值操作将使程序崩溃
	system("pause");
	return 0;
}

线程在函数间的传递

#include <iostream>
#include <thread>
void some_function()
{
	std::cout << "hello" << std::endl;
}
std::thread f0()//函数返回参数
{
	return std::thread(some_function);
}
void f(std::thread t)//函数参数传入
{
	t.detach();//分离
	//t.join();//会合
}
void g()
{
	std::thread t0 = f0();//临时对象,自动移动
	t0.join();
	f(std::thread(some_function));//临时对象,自动移动
	std::thread t(some_function);
	f(std::move(t));//命名对象,显式移动
}
void fun()
{
	std::thread t(some_function);
	t.detach();
	//or join(),此处使得t对应线程销毁前显式等待完成,或者分离出来
}
int main()
{
	fun();
	g();
	system("pause");
	return 0;
}

scoped_thread类:确保线程程序退出前完成

#include <iostream>
#include <thread>
void some_function()
{
	std::cout << "hello" << std::endl;
}
void do_something(const int &i)
{
	std::cout << i << std::endl;
}
class scoped_thread
{
	std::thread t;
public:
	explicit scoped_thread(std::thread t_) : // 1
		t(std::move(t_))
	{
		if (!t.joinable()) // 2
			throw std::logic_error("No thread");
	}
	~scoped_thread()
	{
		t.join(); // 3
	}
	scoped_thread(scoped_thread const&) = delete;
	scoped_thread& operator=(scoped_thread const&) = delete;
};
struct func
{
	int& i;
	func(int& i_) : i(i_) {}
	void operator() ()
	{
		for (unsigned j = 0; j<10; ++j)
		{
			do_something(i); // 潜在访问隐患:悬空引用
			std::cout <<"\t"<< j << std::endl;
		}
	}
};
void f()
{
	int some_local_state{ 0 };
	std::thread t{ func(some_local_state) };//统一初始化方式
	t.join();
	scoped_thread st{ std::thread(func(some_local_state)) }; 
	// 统一初始化方式,以防编译器认为是声明函数
	some_function();
} // 5

int main()
{
	f();
	system("pause");
	return 0;
}

量产线程,等待它们结束

#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
void do_work(unsigned id)
{
	std::cout << id << std::endl;
}
void f()
{
	std::vector<std::thread> threads;
	for (unsigned i = 0; i < 20; ++i)
	{
		threads.push_back(std::thread(do_work, i)); // 产生线程
	}
	std::for_each(threads.begin(), threads.end(),
		std::mem_fn(&std::thread::join)); // 对每个线程调用join(),for_each算法:<alogrithm>
}
int main()
{
	f();
	system("pause");
	return 0;
}
点击打开链接:关于for_each算法中mem_fn的使用。

原生并行版的 std::accumulate

#include <iostream>
#include <thread>
#include <vector>
#include <numeric>
#include <algorithm>
template<typename Iterator, typename T>
struct accumulate_block
{
	void operator()(Iterator first, Iterator last, T& result)
	{
		result = std::accumulate(first, last, result);
	}
};

template<typename Iterator, typename T>
T parallel_accumulate(Iterator first, Iterator last, T init)
{
	unsigned long const length = std::distance(first, last);
	if (!length) // 长度
		return init;
	unsigned long const min_per_thread = 25;//最小处理元素数量
	unsigned long const max_threads =
		(length + min_per_thread - 1) / min_per_thread; // 最大线程数
	unsigned long const hardware_threads =
		std::thread::hardware_concurrency();
	unsigned long const num_threads = // min(最大线程数,硬件支持线程数)=N
		std::min(hardware_threads != 0 ? hardware_threads : 2, max_threads);
	unsigned long const block_size = length / num_threads; //每个线程中处理元素个数
	std::vector<T> results(num_threads);//存储每个线程计算结果,默认初始化为0
	std::vector<std::thread> threads(num_threads - 1); // 新声明N-1个线程对象
	Iterator block_start = first;
	for (unsigned long i = 0; i < (num_threads - 1); ++i)//N-1
	{
		Iterator block_end = block_start;
		std::advance(block_end, block_size); // 算出尾迭代器
		threads[i] = std::thread( // ref,启动N-1个线程,初始函数及参数传入
			accumulate_block<Iterator, T>(),
			block_start, block_end, std::ref(results[i]));
		block_start = block_end; // 更新头迭代器
	}
	accumulate_block<Iterator, T>()(
		block_start, last, results[num_threads - 1]); // 主线程作为第N个线程
	std::for_each(threads.begin(), threads.end(),
		std::mem_fn(&std::thread::join)); // 会合
	return std::accumulate(results.begin(), results.end(), init); // 调用原始算法计算多线程结果
}

int main()
{
	std::vector<int> v(10000000, 3);
	int r0 = parallel_accumulate(v.cbegin(), v.cend(), 0);//135ms
	int r1 = std::accumulate(v.cbegin(), v.cend(), 0);//285ms
	std::cout << r0 << std::endl << r1 << std::endl;
	system("pause");
	return 0;
}
在元素数量较大的时候表现十分不错。

识别线程

1、线程标识类型: std::thread::id 。

2、检索方式:
A、std::thread t; 由t.get_id() 来直接获取。如果 std::thread 对象没有与任何执行线程相关联, get_id() 将返回 std::thread::type 默认构造值,这个值表示“没有线程”。

B、当前线程中调用 std::this_thread::get_id() (这个函数定义在 <thread> 头文件中)也可以获得线程标识。

3、std::thread::id 对象可以自由的拷贝和对比,因为标识符就可以复用。
#include <iostream>
#include <thread>
void fun()
{
	std::cout << "fun()" << std::endl;
}
int main()
{
	std::thread t0{ fun };	
	std::thread t1{ fun };
	t1.detach();
	std::cout <<"子线程\t"<< t0.get_id()<<"\t" << t1.get_id() << std::endl;//默认构造值,没有线程:0
	t0.join();
	std::cout << "主线程\t" << std::this_thread::get_id() << std::endl;
	std::hash<std::thread::id> ha;//待研究使用方法
	system("pause");
	return 0;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值