C++ 11多线程学习笔记

一、多线程小实例

#include <thread>
#include <iostream>
void foo() {
    std::cout << "Hello world" << std::endl;
}
int main() {
    std::thread thread(foo);  // 启动线程foo
    thread.join();  // 等待线程执行完成
    std::cout << "I am coming !" << std::endl;
    return 0;
}

C++11 多线程库 使用std;;thread 实例,此处为一个线程,运行下来跟普通的没什么区别。

运行,程序输出:

Hello world
I am comming !

创建一个双线程的例子:

#include<thread>
#include<iostream>
#include<chrono>
using namespace std::chrono;
void foo(const char*name)
{
   std::this_thread::sleep_for(milliseconds(1000));
   std::cout << "hello " << name <<std::endl;
   for (int i = 0; i < 10; i++)
   {
	std::cout << i << std::endl;
   }
}
void fooo(const char*name)
{
	
	std::cout << "hello " << name << std::endl;
	for (int i = 10; i < 20; i++)
	{
		std::cout << i << std::endl;
	}
}
int main()
{
	std::thread thread(foo,"thread");
	std::thread thread2(fooo, "thread2");
	thread.join();
	thread2.join();
	std::cout << "I am comming "  << std::endl;

	return 0;
}

运行,程序输出:

其中std::this_thread::sleep_for(milliseconds(1000));

为使该线程等待1000ms再执行,估程序先执行了thread2,此时可看成增加线程后与普通函数的不同。

具体函数解析,见下一篇

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值