(一)、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;
}