C++11——多线程编程1
翻译来自:https://thispointer.com//c-11-multithreading-part-1-three-different-ways-to-create-threads/
我们可以使用std::thread对象附加一个回调,当这个新线程启动时,它将被执行。 这些回调可以是,
1、函数指针
2、函数对象
3、Lambda函数
新线程将在创建新对象后立即开始,并且将与已启动的线程并行执行传递的回调。
此外,任何线程可以通过在该线程的对象上调用join()函数来等待另一个线程退出。
看一个主线程创建单独线程的例子,创建完新的线程后,主线程将打印一些信息并等待新创建的线程退出。
函数指针
#include <iostream> #include <thread> void thread_function() { for (int i = 0; i < 100; i++) std::cout << "thread function excuting" << std::endl; } int main() { std::thread threadObj(thread_function); for (int i = 0; i < 100; 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 < 100; i++) std::cout << "Display Thread Excecuting" << std::endl; } }; int main() { std::thread threadObj((DisplayThread())); for (int i = 0; i < 100; 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; }
线程间的区分
每个std::thread对象都有一个相关联的id,可以获取到
std::thread::get_id() :成员函数中给出对应线程对象的id
std::this_thread::get_id() : 给出当前线程的id
如果std::thread对象没有关联的线程,get_id()将返回默认构造的std::thread::id对象:“not any thread”
std::thread::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(); std::cout << "From Main Thread :: ID of Main" << std::this_thread::get_id(); return 0; }