C++多线程helloWord

#include<iostream>
#include<thread>
void hello() {
	std::cout << "Hello Concurrent Word\n";
}
int main() {
	std::thread t(hello);
	t.join();
}

这完全就是大材小用了,但这也正是我们开始学习C++并发编程的第一步,如果想要系统的学习C++的多线程并发。

强烈推荐《C++并发编程第二版》,其所使用标准C++111,C++14,C++17,强烈建议对于新标准新特性不了解的诸位,作者更是ios即C++标准委员会的成员之一,书中内容也有多位成员参与编写与帮助。

同时体会多线程并发的魅力。

 最简单的发起线程

#include<iostream>
#include<thread>
void do_some_work(){}
class background_task {
public:
	void operator()()const {
		do_some_work();
	}
};
int main() {
	background_task f;
	std::thread my_thread(f);
	my_thread.join();
}
//函数对象,lambda表达式,函数指针等都可以,这里是使用函数对象

以及利用rall过程等待线程完结,很多很多等待你的学习

#include<iostream>
#include<thread>
class thread_guard {
	std::thread& t;
public:
	explicit thread_guard(std::thread& t_) :t(t_) {}
	~thread_guard() {
		/* joinabe成员函数的作用在c++官方文档中是返回线程是否是可结合的。. 可结合的意思就是,一个线程是否能够被执行Join或者是detch操作,
		因为相同的线程不能被join两次,也不能join完再进行detach,同理也不可以被detach两次,所以joinable函数就是判断是否能进行可结合。*/
		if (t.joinable()) {
			t.join();
		}
	}
	thread_guard(thread_guard const&) = delete;
	thread_guard& operator=(thread_guard const&) = delete;
};
void do_something() {}
struct func {
	int& i;
	func(int& i_) :i(i_) {}
	void operator()() {
		for (unsigned j = 0; j < 1000000; ++j) {
			do_something();
		}
	}
};
void f() {
	int some_local_state = 0;
	func my_func(some_local_state);
	std::thread t(my_func);
	thread_guard g(t);
	do_something();
}
int main() {
	f();
}
//20面下半部分到21页

请诸位的编译器要支持C++17

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值