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


未完待续

相关推荐
满天点点星辰6 分钟前
Linux命令大全-find命令
linux·运维·服务器
H_z_q240118 分钟前
RHCE的条件测试
linux·运维·服务器
新青年.23 分钟前
【Ubuntu】Ubuntu下解决Chrome不能输入中文
linux·chrome·ubuntu
代码游侠1 小时前
数据结构——哈希表
数据结构·笔记·学习·算法·哈希算法·散列表
风华同学1 小时前
【环境搭建篇】ARM+Linux环境搭建
linux·运维·arm开发
温柔如酒1 小时前
【linux调试】使用 sysrq 快照内核状态堆栈
linux·运维·服务器
van久1 小时前
.Net Core 学习:DbContextOptions<T> vs DbContextOptions 详细解析
java·学习·.netcore
std860211 小时前
Linux 6.18发布:年度最后版本或成新长期支持版本
linux·运维·服务器
HalvmånEver1 小时前
Linux:进程替换(进程控制四)
linux·运维·服务器·学习·进程
一叶之秋14121 小时前
从零开始学Linux进程控制:fork、wait、exec 详解
linux·运维·服务器