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


未完待续

相关推荐
用户31187945592181 天前
Kylin Linux 10 安装 glib2-devel-2.62.5-7.ky10.x86_64.rpm 方法(附安装包)
linux
涛啊涛1 天前
Centos7非LVM根分区容量不足后扩容,对调硬盘挂载/
linux·磁盘管理
CYRUS_STUDIO2 天前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
熊猫李2 天前
rootfs-根文件系统详解
linux
dessler2 天前
Hadoop HDFS-高可用集群部署
linux·运维·hdfs
泽泽爱旅行2 天前
awk 语法解析-前端学习
linux·前端
轻松Ai享生活3 天前
5 节课深入学习Linux Cgroups
linux
christine-rr3 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神5553 天前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆3 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs