1,基本的接口调用
#include <iostream>
#include <thread>
#include <string>
using namespace std;
class MyThread
{
public:
void threadMain()
{
//this_thread::sleep_for(5ms);
cout << "threadMain name = " << this->name << endl;
}
public:
//C++11 可以设定默认值
string name = "小青";
};
int main()
{
MyThread thread1;
thread1.name = "test——1";
thread th1 = thread(&MyThread::threadMain, &thread1);
th1.join();
getchar();
return 0;
}
成员函数做线程的入口时,传参时候 成员函数的地址+ 对象的地址(this指针)。
封装线程基类接口
#include <iostream>
#include <thread>
#include <string>
using namespace std;
//线程基类
class BaseThread
{
public:
virtual void Start()
{
cout << "BaseThread_Start" << endl;
this->is_exit_ = false;
_th = thread(&BaseThread::Func,this);
}
virtual void Wait()
{
if (_th.joinable())
{
_th.join();
}
}
virtual void Stop()
{
this->is_exit_ = true;
Wait();
}
bool is_exit()
{
return is_exit_;
}
private:
bool is_exit_ = false;
std::thread _th;
virtual void Func() = 0;//设计成纯虚函数时,派生类必须实现
};
class TestThread :public BaseThread
{
public:
void Func()override
{
cout << "TestThread func" << endl;
cout << "test_data = " << this->test_data << endl;
while (!is_exit())
{
this_thread::sleep_for(100ms);
cout << "." << flush;//刷新打印显示
}
cout << "线程退出,,,,,,,," << endl;
}
public:
string test_data;
};
int main()
{
TestThread thread1;
thread1.test_data = "test——1";
thread1.Start();
getchar(); //收到键盘动作后 Stop
thread1.Stop();//线程退出
thread1.Wait();
return 0;
}
3,lambda临时函数作为线程入口
lambda函数格式:
[捕捉列表](参数)mutable-> 返回值类型 (函数体)
线程实例:
//带传递参数的
int main()
{
thread t([](int data) {
cout << "t = " << data << endl;
}, 1000
);
t.join();
return 0;
}
成员函数中使用lambda表达式做线程入口:
class LambdaTest
{
public:
void Starat()
{
thread t([this]() {cout << "Lambda testData = " << testData << endl; });
t.join();
}
public:
string testData;
};
int main()
{
LambdaTest test1;
test1.testData = "测试中,,,,,,,";
test1.Starat();
return 0;
}
本文介绍了C++中线程接口的基本使用方法,包括通过成员函数启动线程、封装线程基类接口以及使用lambda表达式作为线程入口。演示了不同场景下线程创建与管理的具体实现。
340

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



