c++多线程编程整理(c++11)

C++11中std命名空间将Boost库中的Thread加入,Boost的多线程从准标准变为标准。头文件为#include,通过std::thread应用,使用过程中要注意join()和detach()的区别。数据同步的时候使用mutex,记得包含#include。

1. 普通函数多线程调用

  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;
}
  1. 有参函数
#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. 在类内部创建线程

  1. 类内部函数为静态函数
#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;
}
  1. 在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()独立于主线程并发执行,主线程后续代码段无需等待。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

an y 5429

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

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

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

打赏作者

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

抵扣说明:

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

余额充值