C++11中std命名空间将Boost库中的Thread加入,Boost的多线程从准标准变为标准。头文件为#include,通过std::thread应用,使用过程中要注意join()和detach()的区别。数据同步的时候使用mutex,记得包含#include。
1. 普通函数多线程调用
- 无参函数
#include <thread>
#include <iostream>
void print(){
std::cout<<"这是一个测试多线程的程序!!"<<std::endl;
}
int main(){
std::thread A(print);
A.join();
std::cout<<"这是主程序!!"<<std::endl;
return 0;
}
- 有参函数
#include <thread>
#include <iostream>
void print(int a, int b){
int c = a+b;
std::cout<<a<<"+"<<b<<"="<<c<<std::endl;
return c;
}
int main(){
std::thread A(print, 3, 4);
A.join();
std::cout<<"这是主程序!!"<<std::endl;
return 0;
}
2. 在类内部创建线程
- 类内部函数为静态函数
#include <thread>
#include <iostream>
class MyThread{
public:
static void Hello(){
std::cout<<"Hello MyThread!!!!"<<std::endl;
}
static void start(){
std::thread td(Hello);
td.join();
}
};
int main(){
MyThread::start();
return 0;
}
- 在Singleton(单例)模式内部创建线程
#include <thread>
#include <iostream>
using namespace std;
class Singleton{
public:
void print(){
cout<<"This is a test thread"<<endl;
}
static void start(){
thread td(bind(&Singleton::print, &Singleton::getInstance()));
td.join();
}
static Singleton& getInstance(){
if(instance==nullptr){
instance = new Singleton();
}
return *instance;
}
private:
Singleton(){};
static Singleton* instance;
};
int main(){
Singleton::start();
return 0;
}
3.用类内部函数在类外部创建线程
#include <thread>
#include <mutex>
using namespace std;
class Foo {
public:
Foo() {
m2.lock();
m3.lock();
}
void first(function<void()> printFirst) {
cout<<"fasd";
printFirst();
m2.unlock();
}
void second(function<void()> printSecond) {
m2.lock();
cout<<"fasd1";
printSecond();
m3.unlock();
}
void third(function<void()> printThird) {
m3.lock();
cout<<"fasd2";
printThird();
m3.unlock();
}
private:
mutex m2, m3;
};
void printFirst(){
cout<<"First"<<endl;
}
void printSecond(){
cout<<"Second"<<endl;
}
void printThird(){
cout<<"Third"<<endl;
}
int main(void) {
Foo f;
thread B(bind(&Foo::second,&f,printSecond));
thread C(bind(&Foo::third,&f,printThird));
thread A(bind(&Foo::first,&f,printFirst));
A.join();
B.join();
C.join();
return 0;
}
4.join()和detach()的区别:
join()的作用是主线程等待子线程结束方可执行下一步(串行),使用detach()独立于主线程并发执行,主线程后续代码段无需等待。