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


未完待续

相关推荐
hsjcjh1 小时前
Nodemailer使用教程:在Node.js中发送电子邮件
linux·运维·node.js
摇滚侠1 小时前
如何选择 nodejs 版本,nodejs 版本号详解
学习
醇氧1 小时前
【学习】IP地址:数字世界的“门牌号”怎么读?
网络协议·学习·tcp/ip
不怕犯错,就怕不做2 小时前
linux 如何查看自己的帐号密码及samba的帐号和密码
linux·运维·服务器
地下核武2 小时前
Ubuntu 24.04 在线安装 Qt 6.10.2 后 Qt Creator 无法启动问题记录与解决
linux·qt·ubuntu
talen_hx2962 小时前
《零基础入门Spark》学习笔记 Day 11
笔记·学习·spark
张3233 小时前
Linux 启动过程
linux·运维
三万棵雪松3 小时前
【Linux 物联网网关主控系统-Linux主控部分(二)】
linux·嵌入式linux
chinesegf3 小时前
ubuntu建虚拟环境制作docker容器
linux·ubuntu·docker