Linux多线程(六)之线程控制4【线程ID及进程地址空间布局】

news2025/6/3 16:25:00

文章目录

      • 线程ID及进程地址空间布局
        • 线程局部存储

线程ID及进程地址空间布局

  1. pthread_ create函数会产生一个线程ID,存放在第一个参数指向的地址中。

    该线程ID和前面说的线程ID不是一回事。

  2. 前面讲的线程ID属于进程调度的范畴。

​ 因为线程是轻量级进程,是操作系统调度器的最小单位,

​ 所以需要一个数值来唯一表示该线程。

​ 用户级线程+内核轻量级进程=Linux线程

​ 线程:用户级线程、内核级线程

Linux线程就是用户级线程

​ 用户级执行流:内核lwp = 1:1

  1. pthread_ create函数第一个参数指向一个虚拟内存单元,

​ 该内存单元的地址即为新创建线程的线程ID,属于NPTL线程库的范畴。

​ 线程库的后续操作,就是根据该线程ID来操作线程的。

  1. 线程库NPTL提供了pthread_ self函数,可以获得线程自身的ID:
pthread_t pthread_self(void);

pthread_self

#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <thread>
#include <string>
#include <cstdlib>

using namespace std;

string tohex(pthread_t tid)
{
    char hex[64];
    snprintf(hex, sizeof(hex), "%p", tid);
    return hex;
}

void *threadroutine(void *args)
{
    while (1)
    {
        cout << "thread id: " << tohex(pthread_self()) << endl;
        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadroutine, (void *)"thread 1");
    cout << "main thread create thread done,new thread id: " << tohex(tid) << endl;
    pthread_join(tid, nullptr);
    return 0;
}

image-20250429132415068

pthread_t 到底是什么类型呢?取决于实现。

对于Linux目前实现的NPTL实现而言,pthread_t类型的线程ID,

本质就是一个进程地址空间上的一个地址。

image-20250425230334017

一个执行流本质就是一条调用链。

调用函数就是在栈帧中为该函数形成栈帧结构。

为了完成临时变量空间在栈帧中的开辟和释放。

验证创建多线程:

makefile

mythread:mythread.cc
	g++ -o $@ $^ -std=c++11 -lpthread
.PHONY:clean
clean:
	rm -rf mythread

mythread.cc

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <vector>

using namespace std;

#define NUM 5

struct threadData
{
    string tname;
};

string toHex(pthread_t tid)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}

void InitThreadData(threadData *td, int i)
{
    td->tname = "thread-" + to_string(i);
}

void *threadRoutine(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    while (i < 5)
    {
        cout << "pid: " << getpid() << " ,tid: " << toHex(pthread_self()) << " ,name: " << td->tname << endl;
        sleep(1);
        i++;
    }
    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData;
        // 使用堆空间 而且每次都是新的堆空间 堆空间是共享的 访问的是堆空间的不同位置
        // 我们让一个线程访问对应的一个堆空间
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
        sleep(1);
    }

    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}

image-20250505145912944

验证每个线程都有独立的栈结构:

void *threadRoutine(void *args)
{
    int test_i=0;
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    while (i < 5)
    {
        cout << "pid: " << getpid() << " ,tid: " << toHex(pthread_self()) 
        << " ,name: " << td->tname <<" ,test_i: "<<test_i<<" ,&test_i: "
        <<toHex((pthread_t)&test_i)<< endl;
        sleep(1);
        i++,test_i++;
    }
    delete td;
    return nullptr;
}

image-20250505151208228

验证每个线程的栈数据是可以被访问的(但是不建议):

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <vector>

using namespace std;

#define NUM 5

int*p;

struct threadData
{
    string tname;
};

string toHex(pthread_t tid)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}

void InitThreadData(threadData *td, int i)
{
    td->tname = "thread-" + to_string(i);
}

void *threadRoutine(void *args)
{
    int test_i=0;
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    if(td->tname=="thread-0")
    {
        p=&test_i;
    }
    while (i < 5)
    {
        cout << "pid: " << getpid() << " ,tid: " << toHex(pthread_self()) 
        << " ,name: " << td->tname <<" ,test_i: "<<test_i<<" ,&test_i: "<<&test_i<< endl;
        sleep(1);
        i++,test_i++;
    }
    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData;
        // 使用堆空间 而且每次都是新的堆空间 堆空间是共享的 访问的是堆空间的不同位置
        // 我们让一个线程访问对应的一个堆空间
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
        // sleep(1);
    }

    sleep(1);//确保赋值成功
    cout<<"main thread get a thread local value,val: "<<*p<<" ,&val: "<<p<<endl;


    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}

image-20250505155535503

线程与线程之间几乎没有秘密

线程栈上的数据,也是可以被其他线程看到并访问的。

线程局部存储
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <vector>

using namespace std;

#define NUM 5

int g_val=0;

struct threadData
{
    string tname;
};

string toHex(pthread_t tid)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}

void InitThreadData(threadData *td, int i)
{
    td->tname = "thread-" + to_string(i);
}

void *threadRoutine(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    while (i < 5)
    {
        cout << "pid: " << getpid() << " ,tid: " << toHex(pthread_self()) 
        << " ,name: " << td->tname <<" ,g_val: "<<g_val<<" ,&g_val: "<<&g_val<< endl;
        sleep(1);
        i++,g_val++;
    }
    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData;
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
        // sleep(1);
	}
    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}

image-20250505160424955

全局变量是被所有的线程同时看到并访问的。

如果线程想要一个私有的全局变量呢??

__thread+变量
__thread int g_val=0;

image-20250505161121658

编译器提供的编译选项

__thread threadData td;

image-20250505161425635

__thread只能用来定义内置类型,不能用来定义自定义类型

作用:可以存储该线程的某些系统调用数据(就不需要频繁调用的系统调用了)。

__thread unsigned int number=0;
__thread int pid=0;

struct threadData
{
    string tname;
};

void *threadRoutine(void *args)
{
    pid=getpid();
    number=pthread_self();
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    while (i < 5)
    {
        cout<<"pid: "<<pid<<" ,tid: "<<number<<endl;
        sleep(1);
        i++,g_val++;
    }
    delete td;
    return nullptr;
}

image-20250505162435763

在调用链上,可以直接获取该线程的pid、tid等。(线程级别的全局变量而且互不干扰)

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

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

相关文章

1.什么是node.js、npm、vue

一、Node.js 是什么&#xff1f; &#x1f63a; 定义&#xff1a; Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境&#xff0c;让你可以在浏览器之外运行 JavaScript 代码&#xff0c;主要用于服务端开发。 &#x1f63a;从计算机底层说&#xff1a;什么是“运…

Xamarin入门笔记(Xamarin已经被MAUI取代)

初级代码游戏的专栏介绍与文章目录-CSDN博客 Xamarin入门 概述 环境 Android开发环境比较简单&#xff0c;自带模拟器&#xff0c;实体机打开开发者模式即可。 iOS开发环境比较复杂&#xff0c;必须搭配Mac电脑&#xff0c;Windows连接Mac开发可能有问题&#xff08;比如发…

排查Oracle文件打开数过多

Oracle数据库在运行过程中&#xff0c;会打开大量的文件以执行其操作&#xff0c;包括数据文件、控制文件、日志文件等。如果Oracle用户打开的文件数过多&#xff0c;可能会引起系统性能下降。下面将深入分析Oracle用户文件打开数的优化策略&#xff0c;以帮助数据库管理员&…

应用层协议http(无代码版)

目录 认识URL urlencode 和 urldecode HTTP 协议请求与响应格式 HTTP 的请求方法 GET 方法 POST 方法 HTTP 的状态码 HTTP 常见 Header Location 关于 connection 报头 HTTP版本 远程连接服务器工具 setsockopt 我们来学习应用层协议http。 虽然我们说, 应用层协…

8.5 Q1|广州医科大学CHARLS发文 甘油三酯葡萄糖指数累积变化与 0-3期心血管-肾脏-代谢综合征人群中风发生率的相关性

1.第一段-文章基本信息 文章题目&#xff1a;Association between cumulative changes of the triglyceride glucose index and incidence of stroke in a population with cardiovascular-kidney-metabolic syndrome stage 0-3: a nationwide prospective cohort study 中文标…

无人机停机坪运行技术分析!

一、运行方式 1. 自动折叠与展开 部分停机坪采用二次折叠设计&#xff0c;通过传动组件实现自动折叠&#xff0c;缩小体积便于运输&#xff1b;展开后最大化停机面积&#xff0c;适应不同任务需求。例如&#xff0c;珠海双捷科技的专利通过两次折叠使停机坪体积最小化&#x…

【Java Web】速通HTML

参考笔记: JavaWeb 速通HTML_java html页面-CSDN博客 目录 一、前言 1.网页组成 1 结构 2 表现 3 行为 2.HTML入门 1 基本介绍 2 基本结构 3. HTML标签 1 基本说明 2 注意事项 4. HTML概念名词解释 二、HTML常用标签汇总 + 案例演示 1. 字体标签 font (1)定义 (2)案例 2…

在线制作幼教早教行业自适应网站教程

你想知道怎么做自适应网站吗&#xff1f;今天就来教你在线用模板做个幼教早教行业的网站哦。 首先得了解啥是自适应网站。简单说呢&#xff0c;自适应网站就是能自动匹配不同终端设备的网站&#xff0c;像手机、平板、电脑等。那如何做幼早教自适应网站呢&#xff1f; 在乔拓云…

Apptrace:APP安全加速解决方案

2021 年&#xff0c;某知名电商平台在 “618” 大促期间遭遇 DDoS 攻击&#xff0c;支付系统瘫痪近 2 小时&#xff1b;2022 年&#xff0c;一款热门手游在新版本上线时因 CC 攻击导致服务器崩溃。观察发现&#xff0c;电商大促、暑期流量高峰和年末结算期等关键商业周期&#…

Web攻防-SQL注入增删改查HTTP头UAXFFRefererCookie无回显报错

知识点&#xff1a; 1、Web攻防-SQL注入-操作方法&增删改查 2、Web攻防-SQL注入-HTTP头&UA&Cookie 3、Web攻防-SQL注入-HTTP头&XFF&Referer 案例说明&#xff1a; 在应用中&#xff0c;存在增删改查数据的操作&#xff0c;其中SQL语句结构不一导致注入语句…

GoldenDB管理节点zk部署

目录 1、准备阶段 1.1、部署规划 1.2、硬件准备 1.3、软件准备 1.4、网络端口开通 1.5、环境清理 2、实施阶段 2.1、操作系统配置 2.1.1、主机名修改 2.1.2、修改hosts文件 2.1.3、禁用防火墙 2.1.4、禁用selinux 2.1.5、禁用透明大页 2.1.6、资源限制调整 2.1.…

mac mini m4命令行管理员密码设置

附上系统版本图 初次使用命令行管理员&#xff0c;让输入密码&#xff0c;无论是输入登录密码还是账号密码&#xff0c;都是错的&#xff0c;百思不得其解&#xff0c;去网上搜说就是登录密码啊 直到后来看到了苹果官方的文档 https://support.apple.com/zh-cn/102367 https…

计算机网络之差错控制中的 CRC(循环冗余校验码)

文章目录 1 概述1.1 简介1.2 特点1.3 基本原则 2 实现步骤3 例题 1 概述 1.1 简介 CRC&#xff1a;Cyclic Redundancy Check&#xff08;循环冗余校验&#xff09;是计算机网络中常用的一种差错控制编码方法&#xff0c;用于检测数据传输或存储过程中可能出现的错误。 1.2 特…

【深度学习】7. 深度卷积神经网络架构:从 ILSVRC、LeNet 到 AlexNet、ZFNet、VGGNet,含pytorch代码结构

深度卷积神经网络架构&#xff1a;从 ILSVRC 到 AlexNet 在2012年Alex出现之前&#xff0c;主要还是依赖于SVM&#xff0c;同时数据工程成为分类任务中很大的一个部分&#xff0c;对数据处理的专家依赖性高。 一、ILSVRC 与图像分类任务背景 ILSVRC 简介 ILSVRC&#xff08…

基于cornerstone3D的dicom影像浏览器 第二十七章 设置vr相机,复位视图

文章目录 前言一、VR视图设置相机位置1. 相机位置参数2. 修改mprvr.js3. 调用流程1) 修改Toolbar3D.vue2) 修改View3d.vue3) 修改DisplayerArea3D.vue 二、所有视图复位1.复位流程说明2. 调用流程1) Toolbar3D中添加"复位"按钮&#xff0c;发送reset事件2) View3d.vu…

2025年渗透测试面试题总结-匿名[校招]高级安全工程师(代码审计安全评估)(题目+回答)

安全领域各种资源&#xff0c;学习文档&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具&#xff0c;欢迎关注。、 目录 匿名[校招]高级安全工程师(代码审计安全评估) 渗透基础 1. 自我介绍 2. SQL注入写Shell&#xff08;分数…

Jenkins实践(7):Publish over SSH功能

在 Jenkins 中使用Publish over SSH功能,需要安装对应的插件。以下是详细步骤: 1. 安装 Publish over SSH 插件 进入 Jenkins 管理界面 → Manage Jenkins → Manage Plugins。切换到 Available 选项卡,搜索 "Publish Over SSH"。勾选插件并点击 Install without…

SQLite 中文写入失败问题总结

SQLite 中文写入失败问题总结与解决方案 在 Windows 下使用 C 操作 SQLite 数据库时&#xff0c;中文字段经常出现 写入成功但内容显示为 BLOB 或 乱码 的问题。根本原因在于 SQLite 要求字符串以 UTF-8 编码 存储&#xff0c;而默认的 std::string 中文通常是 GB2312/ANSI 编…

ubuntu系统安装Pyside6报错解决

目录 1&#xff0c;问题&#xff1a; 2&#xff0c;解决方法&#xff1a; 2.1 首先查看pypi是否有你需要包的镜像&#xff1a; 2.2 其它方案&#xff1a; 2.3 如果下载很慢&#xff0c;可以换源&#xff1a; 2.4 查看系统架构 Windows Ubuntu 1&#xff0c;问题&#xf…

榕壹云医疗服务系统:基于ThinkPHP+MySQL+UniApp的多门店医疗预约小程序解决方案

在数字化浪潮下,传统医疗服务行业正面临效率提升与客户体验优化的双重挑战。针对口腔、美容、诊所、中医馆、专科医院及康复护理等需要预约或诊断服务的行业,我们开发了一款基于ThinkPHP+MySQL+UniApp的多门店服务预约小程序——榕壹云医疗服务系统。该系统通过模块化设计与开…