【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来进行调度的。


未完待续

相关推荐
深紫色的三北六号9 小时前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash13 小时前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI1 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行2 天前
Linux和window共享文件夹
linux
木心月转码ing2 天前
WSL+Cpp开发环境配置
linux
崔小汤呀3 天前
最全的docker安装笔记,包含CentOS和Ubuntu
linux·后端
何中应3 天前
vi编辑器使用
linux·后端·操作系统
何中应3 天前
Linux进程无法被kill
linux·后端·操作系统
何中应3 天前
rm-rf /命令操作介绍
linux·后端·操作系统
何中应3 天前
Linux常用命令
linux·操作系统