转载,来自:(https://thispointer.com/c-11-multithreading-part-1-three-different-ways-to-create-threads/)
C ++ 11多线程–第1部分:创建线程的三种不同方式
在本文中,我们将讨论如何使用std :: thread在C ++ 11中创建线程。
C ++ 11线程库简介
原始C ++标准仅支持单线程编程。新的C ++标准(称为C ++ 11或C ++ 0x)于2011年发布。在C ++ 11中,引入了新的线程库。
要求的编译器:
Linux: gcc 4.8.1(完全并发支持)
Windows: Visual Studio 2012和MingW
如何在Linux上编译: g ++ –std = c ++ 11 sample.cpp -lpthread
C ++ 11中的线程创建
在每个C ++应用程序中,都有一个默认的主线程,即main()函数。在C ++ 11中,我们可以通过创建std :: thread类的对象来创建其他线程。
每个std :: thread对象都可以与一个线程关联。
标头要求:
#include <thread>
std :: thread在构造函数中接受什么?
我们可以在std :: thread对象上附加一个回调,该回调将在新线程启动时执行。这些回调可以是
1.)函数指针
2.)函数对象
3.)Lambda函数
可以这样创建线程对象,
std::thread thObj(<CALLBACK>);
新线程将在创建新对象后立即启动,并将与启动它的线程并行执行传递的回调。
此外,任何线程都可以通过在该线程的对象上调用join()函数来等待另一个线程退出。
让我们看一个示例,其中主线程将创建一个单独的线程。创建此新线程后,主线程将在控制台上打印一些数据,然后等待新创建的线程退出。
让我们使用三种不同的回调机制来实现上述功能,
使用函数指针创建线程
#include <iostream>
#include <thread>
void thread_function() {
for(int i = 0; i < 10000; i++)
std::cout<<"thread function Executing"<<std::endl;
}
int main() {
std::thread threadObj(thread_function);
for(int i = 0; i < 10000; i++)
std::cout<<"Display From MainThread"<<std::endl;
threadObj.join();
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}
使用功能对象创建线程
#include <iostream>
#include <thread>
class DisplayThread {
public:
void operator()() {
for(int i = 0; i < 10000; i++)
std::cout<<"Display Thread Executing"<<std::endl;
}
};
int main() {
std::thread threadObj( (DisplayThread()) );
for(int i = 0; i < 10000; i++)
std::cout<<"Display From Main Thread "<<std::endl;
std::cout<<"Waiting For Thread to complete"<<std::endl;
threadObj.join();
std::cout<<"Exiting from Main Thread"<<std::endl;
return 0;
}
使用Lambda函数创建线程
#include <iostream>
#include <thread>
int main()
{
int x = 9;
std::thread threadObj([]{
for(int i = 0; i < 10000; i++)
std::cout<<"Display Thread Executing"<<std::endl;
});
for(int i = 0; i < 10000; i++)
std::cout<<"Display From Main Thread"<<std::endl;
threadObj.join();
std::cout<<"Exiting from Main Thread"<<std::endl;
return 0;
}
区分线程
每个std :: thread对象都有一个关联的ID,我们可以使用进行获取,成员函数,给出相关线程对象的ID,即
std::thread::get_id()
要获取当前线程使用的标识符,
std :: this_thread :: get_id ()
如果std :: thread对象没有关联的线程,则get_id()将返回默认构造的std :: thread :: id对象,即“没有任何线程”。
std :: thread :: id是一个Object,它也可以比较并在控制台上打印。让我们看一个例子,
#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;
}