栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++多线程helloWord

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++多线程helloWord

#include
#include
void hello() {
	std::cout << "Hello Concurrent Wordn";
}
int main() {
	std::thread t(hello);
	t.join();
}

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

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

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

 最简单的发起线程

#include
#include
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
#include
class thread_guard {
	std::thread& t;
public:
	explicit thread_guard(std::thread& t_) :t(t_) {}
	~thread_guard() {
		
		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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/836082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号