一, 创建多线程
-
通过线程函数创建
#include <iostream>
#include <thread>
void func1()
{
std::<< cout << "this is a thread function" << std::endl;
return ;
}
void func2(int a, int b)
{
std::cout << "a + b = " << a + b << std::endl;
return ;
}
int main()
{
std::thread th1(func1);
if (th1.joinable())
{
th1.join();
}
std::thread th2(func2, 1, 2);
if (th2.joinable())
{
th2.join();
}
return 0;
}
-
Lambada表达式创建
#include <iostream>
#include <thread>
void func(int a, int b)
{
std::cout << "a + b = " << a + b << std::endl;
return ;
}
int main()
{
auto lambda = []()
{
func(1, 2);
};
std::thread th1(lambda);
if (th1.joinable())
{
th1.join();
}
return 0;
}
- 使用类对象的成员函数
#include <iostream>
#include <memory>
#include <thread>
class funcClass
{
void print()
{
std::cout << "A\n";
}
};
int main()
{
std::shared_ptr<funcClass > tempClass = std::make_shared<funcClass >();
auto func = [&]()
{
tempClass->print();
};
std::thread th1(func);
if (th1.joinable())
{
th1.join();
}
return 0;
}