C++11多线程编程基础入门

1.在C++11中创建新线程

  在每个c++应用程序中,都有一个默认的主线程,即main函数,在c++11中,我们可以通过创建std::thread类的对象来创建其他线程,每个std :: thread对象都可以与一个线程相关联,只需包含头文件< thread>。可以使用std :: thread对象附加一个回调,当这个新线程启动时,它将被执行。 这些回调可以为函数指针、函数对象、Lambda函数。
  线程对象可通过std::thread thObj(< CALLBACK>)来创建,新线程将在创建新对象后立即开始,并且将与已启动的线程并行执行传递的回调。此外,任何线程可以通过在该线程的对象上调用join()函数来等待另一个线程退出。
  使用函数指针创建线程:

//main.cpp
#include <iostream>
#include <thread>

void thread_function() {
    for (int i = 0; i < 5; i++)
        std::cout << "thread function excuting" << std::endl;
}

int main() {
    std::thread threadObj(thread_function);
    for (int i = 0; i < 5; 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;
}

CmakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(Thread_test)
set(CMAKE_CXX_STANDARD 11)
find_package(Threads REQUIRED)
add_executable(Thread_test main.cpp)
target_link_libraries(Thread_test ${CMAKE_THREAD_LIBS_INIT})

  每个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。

2.joining和detaching 线程

  启动了线程,你需要明确是要等待线程结束(加入式),还是让其自主运行(分离式),一个是通过调用std::thread对象上调用join()函数等待这个线程执行完毕:

std::thread threadObj(funcPtr); 
threadObj.join();

例如,主线程启动10个线程,启动完毕后,main函数等待他们执行完毕,join完所有线程后,main函数继续执行:

#include <iostream>
#inc
  • 0
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值