在本文中,我们将讨论如何使用std::thread
在c++ 11中创建线程。
1.C++11中5种创建线程方法
- 函数指针——这是创建线程的基本形式。
Lambda
函数- 仿函数(函数对象)
- 非静态成员函数
- 静态成员函数
注意:如果我们同时创建多个线程,它不能保证哪个线程会先启动。
如何在Linux上编译:g++ -std =c++11 sample.cpp -lpthread
1.1函数指针
#include <thread>
#include <iostream>
void fun(int x)
{
while(x-->0)
{
std::cout<< x<<std::endl;
}
}
int main()
{
std::thread t1(fun, 11);
t1.join();
return 0;
}
1.2Lambda函数
#include <thread>
#include <iostream>
using namespace std;
int main()
{
auto fun = [](int x){
while (x-- >0)
{
cout << x << endl;
}
};
std::thread t(fun, 10);
t.join();
return 0;
}
我们可以在线程创建时直接使用lambda
#include <thread>
#include <iostream>
using namespace std;
int main()
{
std::thread t([](int x){
while (x-- >0)
{
cout << x << endl;
}
}, 10);
t.join();
return 0;
}
1.3仿函数
#include <thread>
#include <iostream>
using namespace std;
class Base
{
public:
void operator()(int x)
{
while(x-->0)
{
cout<<x<<endl;
}
}
};
int main()
{
std::thread t(Base(), 10);
t.join();
return 0;
}
1.4非静态成员函数
#include <thread>
#include <iostream>
using namespace std;
class Base
{
public:
void run(int x)
{
while(x-->0)
{
cout<<x<<endl;
}
}
};
int main()
{
Base b;
std::thread t(&Base::run, &b, 10);
t.join();
return 0;
}
1.5静态成员函数
#include <thread>
#include <iostream>
using namespace std;
class Base
{
public:
static void run(int x)
{
while(x-->0)
{
cout<<x<<endl;
}
}
};
int main()
{
std::thread t(&Base::run, 10);
t.join();
return 0;
}
2.区分线程
每个std::thread对象都有一个相关联的ID,我们可以使用成员函数std::thread::get_id()
,得到关联线程对象的id。使用std::this_thread::get_id()
获取当前线程的ID。
#include <iostream>
#include <thread>
void thread_function()
{
std::cout<<"Inside Thread :: ID = "<<std::this_thread::get_id()<<std::endl;
}
int main()
{
std::thread threadObj1(thread_function);
std::thread threadObj2(thread_function);
if(threadObj1.get_id() != threadObj2.get_id())
std::cout<<"Both Threads have different IDs"<<std::endl;
std::cout<<"From Main Thread :: ID of Thread 1 = "<<threadObj1.get_id()<<std::endl;
std::cout<<"From Main Thread :: ID of Thread 2 = "<<threadObj2.get_id()<<std::endl;
threadObj1.join();
threadObj2.join();
return 0;
}
参考目录
https://www.youtube.com/watch?v=hCvc9y39RDw
https://thispointer.com/c-11-multithreading-part-1-three-different-ways-to-create-threads/