C++ Multithreading (1) -- creating threads

这篇博客介绍了C++ 11开始支持的多线程概念,详细讲解如何创建线程,包括使用函数指针、函数对象和lambda表达式。此外,还阐述了获取线程ID的方法。
摘要由CSDN通过智能技术生成

introduction

一开始,C++是不支持多线程的,直到C++ 11开始,才真正引入了多线程这个概念和标准库。
如果想在cpp文件,比如project.cpp里面使用多线程,需要引入header file

#include <thread>

在编译的时候,需要使用-lpthread:

g++ project.cpp -lpthread

thread creation

每个C++ application里面都有一个默认线程main。如果我们想要创建额外的线程,首先需要创建std::thread class的objects。每一个std::thread object是和一个thread绑定到一起的。将一个callback function与std::thread object绑定到一起,线程开始运行的时候,这个callback function就会被执行:

std::thread thread_object(CALLBACK)

CALLBACK可以是以下三种之一:

  1. function pointer
  2. function objects what is function object
  3. lambda function what is lambda function

creating threads with function pointer

#include <iostream>
#include <thread>
#include <string>

void worker(int tid, const std::string& name){
   
	for(int i = 0; i < 3; ++i){
   
		std::cout << "woker " << tid << name << " is working" << std::endl;
	}
	std::cout << "worker exits" << std::endl;
}

int main(){
    
	std::thread thread_obj_1(worker, 0, std::string(" Alice"));// worker是function pointer, 
	std::thread thread_obj_2(worker, 1, std::string(" Bob"));  // 1和std::strin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值