【C++上层应用】4. 多线程

文章目录

  • 【 1. 创建线程 】
  • 【 2. 终止线程 】
  • 【 3. 实例 】
  • 【 4. 向线程传递参数 】
  • 【 5. 连接和分离线程 】

  • 多线程 是多任务处理的一种特殊形式,多任务处理允许让电脑同时运行两个或两个以上的程序。
  • 一般情况下,两种类型的多任务处理:基于进程和基于线程
    • 基于进程 的多任务处理是程序的并发执行。
    • 基于线程 的多任务处理是同一程序的片段的并发执行。
  • 多线程程序包含可以同时运行的两个或多个部分。这样的程序中的每个部分称为一个 线程,每个线程定义了一个单独的执行路径。

【 1. 创建线程 】

  • 创建一个 POSIX 线程:
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 
  • 在这里,pthread_create 创建一个新的线程,并让它可执行。下面是关于参数的说明:
参数描述
thread指向线程标识符指针。
attr一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。
start_routine线程运行函数起始地址,一旦线程被创建就会执行。
arg运行函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。
  • 创建线程成功时,函数返回 0,若返回值不为 0 则说明创建线程失败。

【 2. 终止线程 】

  • pthread_exit 用于显式地退出一个线程。通常情况下,pthread_exit() 函数是在线程完成工作后无需继续存在时被调用。
#include <pthread.h>
pthread_exit (status) 
  • 如果 main() 是在它所创建的线程之前结束,并通过 pthread_exit() 退出,那么其他线程将继续执行。否则,它们将在 main() 结束时自动被终止。

【 3. 实例 】

  • 实例1:
    使用 pthread_create() 函数创建了 5 个线程,每个线程输出"Hello Nowcoder!"
#include <iostream>
// 必须的头文件
#include <pthread.h>using namespace std;#define NUM_THREADS 5// 线程的运行函数
void* say_hello(void* args)
{cout << "Hello Nowcoder!" << endl;return 0;
}int main()
{// 定义线程的 id 变量,多个变量使用数组pthread_t tids[NUM_THREADS];for(int i = 0; i < NUM_THREADS; ++i){//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数int ret = pthread_create(&tids[i], NULL, say_hello, NULL);if (ret != 0){cout << "pthread_create error: error_code=" << ret << endl;}}//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;pthread_exit(NULL);
}

使用 -lpthread 库编译下面的程序:

$ g++ test.cpp -lpthread -o test.o

运行结果如下:

$ ./test.o
Hello Nowcoder!
Hello Nowcoder!
Hello Nowcoder!
Hello Nowcoder!
Hello Nowcoder!
  • 实例2:
    用 pthread_create() 函数创建了 5 个线程,并接收传入的参数。每个线程打印一个 “Hello Nowcoder!” 消息,并输出接收的参数,然后调用 pthread_exit() 终止线程。
//文件名:test.cpp#include <iostream>
#include <cstdlib>
#include <pthread.h>using namespace std;#define NUM_THREADS     5void *PrintHello(void *threadid)
{  // 对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取int tid = *((int*)threadid);cout << "Hello Nowcoder! 线程 ID, " << tid << endl;pthread_exit(NULL);
}int main ()
{pthread_t threads[NUM_THREADS];int indexes[NUM_THREADS];// 用数组来保存i的值int rc;int i;for( i=0; i < NUM_THREADS; i++ ){      cout << "main() : 创建线程, " << i << endl;indexes[i] = i; //先保存i的值// 传入的时候必须强制转换为void* 类型,即无类型指针        rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&(indexes[i]));if (rc){cout << "Error:无法创建线程," << rc << endl;exit(-1);}}pthread_exit(NULL);
}

编译并执行程序,将产生下列结果:

$ g++ test.cpp -lpthread -o test.o
$ ./test.o
main() : 创建线程, 0
main() : 创建线程, 1
Hello Nowcoder! 线程 ID, 0
main() : 创建线程, Hello Nowcoder! 线程 ID, 21main() : 创建线程, 3
Hello Nowcoder! 线程 ID, 2
main() : 创建线程, 4
Hello Nowcoder! 线程 ID, 3
Hello Nowcoder! 线程 ID, 4

【 4. 向线程传递参数 】

  • 实例
    通过结构传递多个参数。我们可以在线程回调中传递任意的数据类型,因为它指向 void
#include <iostream>
#include <cstdlib>
#include <pthread.h>using namespace std;#define NUM_THREADS     5struct thread_data{int  thread_id;char *message;
};void *PrintHello(void *threadarg)
{struct thread_data *my_data;my_data = (struct thread_data *) threadarg;cout << "Thread ID : " << my_data->thread_id ;cout << " Message : " << my_data->message << endl;pthread_exit(NULL);
}int main ()
{pthread_t threads[NUM_THREADS];struct thread_data td[NUM_THREADS];int rc;int i;for( i=0; i < NUM_THREADS; i++ ){cout <<"main() : creating thread, " << i << endl;td[i].thread_id = i;td[i].message = (char*)"This is message";rc = pthread_create(&threads[i], NULL,PrintHello, (void *)&td[i]);if (rc){cout << "Error:unable to create thread," << rc << endl;exit(-1);}}pthread_exit(NULL);
}

编译并执行程序,将产生下列结果:

$ g++ -Wno-write-strings test.cpp -lpthread -o test.o
$ ./test.o
main() : creating thread, 0
main() : creating thread, 1
Thread ID : 0 Message : This is message
main() : creating thread, Thread ID : 21Message : This is message
main() : creating thread, 3
Thread ID : 2 Message : This is message
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 4 Message : This is message

【 5. 连接和分离线程 】

  • 使用以下两个函数可以连接或分离线程:
pthread_join (threadid, status) 
pthread_detach (threadid) 

pthread_join() 子程序阻碍调用程序,直到指定的 threadid 线程终止为止。当创建一个线程时,它的某个属性会定义它是否是可连接的(joinable)或可分离的(detached)。只有创建时定义为可连接的线程才可以被连接。如果线程创建时被定义为可分离的,则它永远也不能被连接。

  • 实例:
    使用 pthread_join() 函数来等待线程的完成。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>using namespace std;#define NUM_THREADS     5void *wait(void *t)
{int i;long tid;tid = (long)t;sleep(1);cout << "Sleeping in thread " << endl;cout << "Thread with id : " << tid << "  ...exiting " << endl;pthread_exit(NULL);
}int main ()
{int rc;int i;pthread_t threads[NUM_THREADS];pthread_attr_t attr;void *status;// 初始化并设置线程为可连接的(joinable)pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);for( i=0; i < NUM_THREADS; i++ ){cout << "main() : creating thread, " << i << endl;rc = pthread_create(&threads[i], NULL, wait, (void *)&i );if (rc){cout << "Error:unable to create thread," << rc << endl;exit(-1);}}// 删除属性,并等待其他线程pthread_attr_destroy(&attr);for( i=0; i < NUM_THREADS; i++ ){rc = pthread_join(threads[i], &status);if (rc){cout << "Error:unable to join," << rc << endl;exit(-1);}cout << "Main: completed thread id :" << i ;cout << "  exiting with status :" << status << endl;}cout << "Main: program exiting." << endl;pthread_exit(NULL);
}

编译并执行程序,将产生下列结果:

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread 
Thread with id : 4  ...exiting 
Sleeping in thread 
Thread with id : 3  ...exiting 
Sleeping in thread 
Thread with id : 2  ...exiting 
Sleeping in thread 
Thread with id : 1  ...exiting 
Sleeping in thread 
Thread with id : 0  ...exiting 
Main: completed thread id :0  exiting with status :0
Main: completed thread id :1  exiting with status :0
Main: completed thread id :2  exiting with status :0
Main: completed thread id :3  exiting with status :0
Main: completed thread id :4  exiting with status :0
Main: program exiting.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/157522.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JOSEF 静态中间继电器 ZJY-420 DC220V 板前接线,带底座 增加触点

系列型号&#xff1a; ZJY-400中间继电器&#xff1b;ZJY-600中间继电器&#xff1b; ZJY-800中间继电器&#xff1b;ZJY-020中间继电器&#xff1b; ZJY-040中间继电器&#xff1b;ZJY-060中间继电器&#xff1b; ZJY-006中间继电器&#xff1b;ZJY-008中间继电器&#xff1b;…

git仓库迁移

标题目录 1 下载仓库镜像到本地2 进入本地镜像仓库3 将仓库中的旧的服务端地址更改为新仓库地址4 将修改后的Git镜像仓库推送到新的仓库 1 下载仓库镜像到本地 git clone --mirror xxx/xxx/old.git&#xff08;旧库地址&#xff09;2 进入本地镜像仓库 cd oldUrl.git (旧库名…

SD-WAN技术:重新定义网络连接方式

随着数字化转型的不断加速&#xff0c;企业对网络的需求呼之欲出。传统的WAN网络由于配置复杂、成本高昂以及带宽利用率低等问题而面临挑战。这时SD-WAN技术的出现正好派上了用场&#xff0c;通过其虚拟化、自动化和智能化的技术手段&#xff0c;大幅度提高了企业网络性能和可靠…

内存屏障与JVM指令

内存屏障是一种同步原语&#xff0c;用于确保在并发程序中&#xff0c;当一个线程对内存中的数据进行修改后&#xff0c;其他线程可以及时地获取到最新的数据。 内存屏障可以确保指令的执行具有原子性、可见性和顺序性。在JVM中&#xff0c;内存屏障通常通过插入一段特殊的指令…

Ps:裁剪工具 - 裁剪预设的应用

裁剪工具提供了两种类型的裁剪方式。 一种是仅按宽高比&#xff08;比例&#xff09;进行裁剪&#xff0c;常在对图像进行二次构图时采用。 另一种则按指定的图像尺寸&#xff08;宽度值和高度值&#xff09;及分辨率&#xff08;宽 x 高 x 分辨率&#xff09;进行裁剪。其实质…

关于一些网络的概述

语义分割网络是一种基于深度学习的计算机视觉技术,它能够将图像中的每个像素分配给特定的类别,从而实现对图像中不同对象的精确识别和定位。近年来,随着深度学习技术的不断发展,语义分割网络在各个领域都取得了显著的进展。 早期的语义分割网络主要采用全卷积神经网络(FC…

ES6 class类

基本介绍 1. constructor constructor()方法是类的默认方法&#xff0c;通过new命令生成对象实例时&#xff0c;自动调用该方法。 一个类必须有constructor()方法&#xff0c;如果没有显式定义&#xff0c;一个空的constructor()方法会被默认添加。如&#xff1a; class Po…

scala的schema函数(算子)

在翻阅一些代码的时候&#xff0c;schema算子好像没碰到过&#xff0c;比较好奇structField这个类型&#xff0c;为什么可以直接用name参数&#xff0c;就翻阅了下资料&#xff1a; 在 Apache Spark 中&#xff0c;DataFrame 是一种分布式的数据集&#xff0c;它是以类似于关系…

OFI libfabric原理及应用解析

Agenda 目录/议题 编译通信软件硬件和软件带来的挑战为什么需要libfabriclibfabric架构API分组socket应用 VS libfabric应用区别GPU数据传输示例 编译通信软件 可靠面向连接的TCP和无连接的数据报UDP协议高性能计算HPC或人工智能AI 软硬件复杂性带来的挑战 上千个节点的集群, …

8.Gin 自定义控制器

8.Gin 自定义控制器 前言 在上一篇路由文件抽离的过程中&#xff0c;我们发现接口的业务逻辑还写在路由配置中&#xff0c;如下&#xff1a; 1696385129126 但是如果业务逻辑比较多&#xff0c;如果写在路由之中&#xff0c;肯定不合适。 我们可以将业务逻辑抽离&#xff0c;单…

使用Pytorch实现linear_regression

使用Pytorch实现线性回归 # import necessary packages import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt# Set necessary Hyper-parameters. input_size 1 output_size 1 num_epochs 60 learning_rate 0.001# Define a Toy datas…

操作系统 应用题 例题+参考答案(考研真题)

1.&#xff08;考研真题&#xff09;一个多道批处理系统中仅有P1和P2两个作业&#xff0c;P2比P1晚5ms到达&#xff0c;它们的计算和I/O操作顺序如下。 P1&#xff1a;计算60ms&#xff0c;I/O 80ms&#xff0c;计算20ms。 P2&#xff1a;计算120ms&#xff0c;I/O 40ms&…

<Linux>权限管理|权限分类|权限设置|权限掩码|粘滞位

文章目录 Linux权限的概念Linux权限管理a. 文件访问者的分类b. 文件类型和访问权限c. 文件权限表示方法d. 文件权限的设置权限掩码file指令粘滞位 权限总结权限作业 Linux权限的概念 Linux下有两种用户&#xff1a;超级用户(root)和普通用户。 超级用户&#xff1a;可以在Lin…

学生党的福利!移动云重磅升级存储产品体系

如今&#xff0c;随着科学技术不断发展进步&#xff0c;电子产品的生产技术也变得越来越成熟。一方面&#xff0c;电子产品的功能越来越强大&#xff0c;质量越来越可靠&#xff1b;另一方面&#xff0c;产品价格越来越便宜&#xff0c;在人们生活中越来越普及。大学生群体可以…

基于纳什博弈的多微网主体电热双层共享策略(matlab代码)

目录 ​1 主要内容 2 部分代码 3 程序结果 4 下载链接 ​1 主要内容 该程序复现《Multi-Micro-Grid Main Body Electric Heating Double-Layer Sharing Strategy Based on Nash Game》模型&#xff0c;主要做的是构建基于纳什博弈的多微网主体电热双层共享模型&#xff0c;…

[笔记] 错排问题 #错排

参考&#xff1a;刷题笔记-错排问题总结 错排问题&#xff1a; 一个n个元素的排列&#xff0c;若一个排列中所有的元素都不在自己原来的位置上&#xff0c;那么这样的一个排列就称为原排列的一个错排。而研究一个排列的错排个数的问题&#xff0c;就称为错排问题&#xff08;或…

java项目之木里风景文化管理平台(ssm+vue)

项目简介 木里风景文化管理平台实现了以下功能&#xff1a; 前台功能&#xff1a;用户进入系统可以实现首页&#xff0c;旅游公告&#xff0c;景区&#xff0c;景区商品&#xff0c;景区美食&#xff0c;旅游交通工具&#xff0c;红黑榜&#xff0c;个人中心&#xff0c;后台…

squid代理服务器(传统代理、透明代理、反向代理、ACL、日志分析)

一、Squid 代理服务器 &#xff08;一&#xff09;代理的工作机制 1、代替客户机向网站请求数据&#xff0c;从而可以隐藏用户的真实IP地址。 2、将获得的网页数据&#xff08;静态 Web 元素&#xff09;保存到缓存中并发送给客户机&#xff0c;以便下次请求相同的数据时快速…

【洛谷 B2001】入门测试题目 题解(模拟算法+顺序结构)

入门测试题目 题目描述 求两个整数的和。 输入格式 一行&#xff0c;两个用空格隔开的整数。 输出格式 两个整数的和。 样例 #1 样例输入 #1 1 2样例输出 #1 3样例 #2 样例输入 #2 10230 21312样例输出 #2 31542提示 对于 100 % 100\% 100% 的数据&#xff0c;输…

MySQL 插件之 连接控制插件(Connection-Control)

插件介绍 MySQL 5.7.17 以后提供了Connection-Control插件用来控制客户端在登录操作连续失败一定次数后的响应的延迟。该插件可有效的防止客户端暴力登录的风险(攻击)。该插件包含以下2个组件 CONNECTION_CONTROL&#xff1a;用来控制登录失败的次数及延迟响应时间CONNECTION_C…