c++创建线程

C++11 中 STL 库引入了对多线程的支持,头文件<thread>

进程是系统分配资源的基本单元,线程是操作系统调度的最小单位
程序的实际运行是通过线程来完成的,线程由进程创建,一个进程可以有多个线程
每个线程都有自己独立的栈和局部变量,但它们共享进程的以下资源:
        地址空间
        全局变量
        堆空间
       CPU 时间片
       文件描述符等

所有程序都会有一个主线程,从 main函数开始执行,进程可以比作一间教室,线程则是教室里的每个学生,每个学生是独立的,但他们共享教室中的资源

用全局函数创建线程         thread 线程名(函数名,参数)

#include <iostream>
using namespace std;
#include <thread>
void test(int val) {
	cout << "this is a quanju function,val is: "<< val << endl;
}
int main() {
	thread t1(test,666);
	t1.join();
}

join阻塞函数,告诉主线程,等子线程结束后,再继续执行主线程,主线程一结束,程序就结束

用成员函数创建线程    thread 线程名(&类名::成员函数名,对象,成员函数参数)

#include <iostream>
using namespace std;
#include <thread>
class A {
public:
	void output(int val) const{
		cout << "this is a chengyuan function,val is val" << endl;
	}
};
int main() {
	A a;
	thread t2(&A::output,a,888);
	t2.join();
}

用匿名函数创建线程

#include <iostream>
using namespace std;
#include <thread>

int main() {
	thread t3([] {cout << "this is a noname function" << endl; });
	t3.join();
}

stl库的线程具有跨平台的能力,有了thread依赖库,线程才能运行,vs默认有thread依赖库,linux默认是没有thread依赖库,编译时,需要添加-lphread选项,链接POSIX线程库

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码成行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值