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线程库
714

被折叠的 条评论
为什么被折叠?



