【C/C++】开启线程

该博客围绕C/C++开启线程展开,介绍了创建线程函数,包括各参数如thread、attr、start_routine、arg的含义;阐述了执行流程,给出代码示例;还对相关函数如sleep、pthread_join等进行讲解,同时提到编译时需加参数及cmake配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C/C++开启线程

1 创建线程函数介绍

C/C++开启线程使用 int pthread_create(thread, attr, start_routine, arg) 函数

参数讲解

thread
需要传入一个 pthread_t 变量的地址,比如 pthread mythread;

attr
设置线程的属性,默认为 NULL

start_routine
线程执行函数的指针,比如 void * myThread(void * arg)

arg
执行函数的参数,只能传入一个参数,如果有多个参数则需要用结构体或者对象进行包装

2 执行流程

1.创建pthread
2.实现线程执行过程
3.创建执行对象并执行
4.等待线程执行完毕
5.主函数执行完毕结束

3 代码示例

#include <iostream>
#include <pthread.h>
#include <unistd.h>

/**
 * 定义线程任务实现
 * 传入线程编号
 */
void * myThread(void * arg)
{
  std::cout << "start my task !!!" << std::endl;
  for (int i = 0; i < 5; i++) 
  {
    std::cout << "thread is working " << std::endl;
    sleep(1);
  }
  return 0;
}

int main()
{
  pthread_t pthread;
  int result = pthread_create(&pthread, NULL, myThread, NULL);
  std::cout << "start my thread, result is " << result << std::endl;
  
  // 这一句如果删除的话,主线程在开启子线程后就结束了,因此会无法看拿到子线程执行过程
  pthread_join(pthread, NULL);
  
  return 0;
}

4 函数讲解

sleep
需要使用 unistd.h 头文件,用于执行线程休眠,单位为1s

pthread.h
多线程头文件,包含管理线程的所有函数

编译参数
因为加入了多线程,所以在编译时需要加上参数 -pthread

pthread_join
阻塞等待线程执行结束,获取线程执行状态

cmake增加配置如下:

set(CMAKE_CXX_FLAGS "${CAMKE_CXX_FLAGS} -std=c++11 -pthread")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值