【Linux】多线程_1

文章目录


九、多线程

1. 线程概念

我们知道:进程 = 内核数据结构 + 进程代码和数据 。那什么是线程呢?线程是进程内部的一个执行分支。一个进程内部可以有多个执行流(内核数据结构),这些执行流都是线程。线程是CPU调度的基本单位。

2. 线程的控制

pthread_create函数可以创建一个线程。并且编译时需要软链接 pthread 这个库 。
Makefile:

cpp 复制代码
test_thread: testThread.cc
	g++ -o $@ $^ -std=c++11 -lpthread
.PHONY: clean
clean:
	rm -f test_thread

test_Thread:

cpp 复制代码
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

// 新线程
void* newpthreadrun(void* arg)
{
    while (true)
    {
        cout << "I am newpthreadrun thread" << endl;
        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, newpthreadrun, nullptr);

    // main 线程
    while (true)
    {
        cout << "I am main thread" << endl;
        sleep(1);
    }

    return 0;
}

并且此时只有一个进程在执行:

刚跟我们说了,线程是CPU调度的基本单位,但是CPU怎么区分一个进程里的线程呢?线程有自己的线程id(LWP),CPU调度其实是根据线程id来进行调度的。


未完待续

相关推荐
ltl21 小时前
eBPF 可观测性全景:bcc、bpftrace、libbpf 的工程路径
linux
2401_8685347821 小时前
数仓开发落地手册
linux·运维
正在走向自律1 天前
使用atop工具监控Linux系统指标
linux·运维·php·实时监控·atop分析内存
云深处@1 天前
【数据库】MySQL 入门
数据库·学习·mysql
果果燕1 天前
实习笔记(一):NFS、Samba、VNC、Git、CMake、systemd、内核、交叉编译
linux·arm开发·c++·笔记·git
HyperAI超神经1 天前
【vLLM 学习】Disaggregated Prefill
人工智能·深度学习·学习·vllm
天吾cc1 天前
RTT-IO设备模型
单片机·嵌入式硬件·学习
美味蛋炒饭.1 天前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
yyy(十一月限定版)1 天前
017【入门】最小栈
linux·运维·服务器
呼噜想睡觉1 天前
Bootstrap 组件之响应式导航条实现
学习