C++ std::thread多线程详解

本文详细介绍了C++中std::thread的使用,包括通过函数指针、Lambda表达式、functor、非静态成员函数和静态成员函数创建线程。同时,探讨了如何通过join和detach函数来停止线程。此外,还讲解了std::mutex锁在多线程同步中的应用,确保资源的安全访问。

(一)、std::thread线程创建
1、函数指针
#include <thread>
#include <iostream>

using namespace std;

void funcThread(int x) 
{
	cout << x << endl;
}

int main() 
{
    std::thread tthread001(funcThread, 100);
    tthread001.join();
    return 0;
}
2、Lambda函数
#include <thread>
#include <iostream>

using namespace std;

int main() 
{
    std::thread tthread001(
    [](int x)
    {
    	cout << x << endl;
    }
    , 100);
    tthread001.join();
    return 0;
}
3、functor (Funciton Object)
#include <thread>
#include <iostream>

using namespace std;

class ST_MSG1
{
public:
    void operator()(int x) 
    {
    	cout << x << endl;
    }
};

int main() 
{
    thread t(ST_MSG1(), 100);
    t.join();
    return 0;
}
4、非静态成员函数
#include <thread>
#include <iostream>

using namespace std;

class ST_MSG1 
{
public:
    void fun(int x)
    {
   		cout << x << endl;
    }
};

int main() 
{
    ST_MSG1 b;
    thread t(&ST_MSG1::fun,&b, 100);
    t.join();
    return 0;
}
5、静态成员函数
#include <thread>
#include <iostream>

using namespace std;

class ST_MSG1
 {
public:
    static void fun(int x)
    {
   		cout << x << endl;
    }
};

int main() 
{
    thread t(&ST_MSG1::fun, 100);
    t.join();
    return 0;
}
(二)、std::thread线程停止
1、join函数
  • join函数,一旦线程开始,我们要想等待线程完成,需要在该对象上调用join()
#include <thread>
#include <iostream>

using namespace std;

int main() 
{
    std::thread tthread001(
    [](int x)
    {
    	cout << x << endl;
    }
    , 100);
    tthread001.join();
    return 0;
}
2、detach函数
  • detach函数是分离线程,分离的线程,主线程对它没有管理权限
#include <thread>
#include <iostream>

using namespace std;

int main() 
{
    std::thread tthread001(
    [](int x)
    {
    	cout << x << endl;
    }
    , 100);
    tthread001.detach();       
    return 0;
}
(三)、std::mutex锁
#include <thread>
#include <iostream>

using namespace std;

int main() 
{
	std::mutex mutTest;
    std::thread tthread001(
    [](int x)
    {
    	// 1、加锁、解锁
    	mutTest.lock();
    	cout << x << endl;
    	mutTest.unlock();
    	// 2、作用域内加锁
    	{
    		lock_guard<mutex> lock(mutTest);      // c++17后可写成 lock_guard lock(mutTest);
    		cout << x << endl;
    	}
    }
    , 100);
    tthread001.detach();
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值