Linux系统编程:多线程编程

1. 什么是线程

线程是比进程更小的能独立运行的基本单位,线程基本上不拥有系统资源

一个进程下可以开多个线程,这些线程是并发的

在这里插入图片描述查看线程命令

命令 含义
ps -T -p -T开启线程查看
top -H -p -H开启线程查看

文件书写

文件 含义
/proc/{PID}/task/ 线程默认的名字和进程名相同
/proc/{PID}/task/{tid}/comm 线程名

2. 操作

操作 函数
线程标识 pthread_t pthread_self(void)
线程创建 int pthread_create(pthread_t * tidp, pthread_attr_t * attr, void *(*start_rtn)(void), void * arg)
子线程终止 void pthread_exit(void* retval)
线程合并 int pthread_join(pthread_t tid, void **retval)
线程分离 int pthread_detach(pthread_t tid)
发送信号 int pthread_kill(pthread_t tid, int sig)

线程标识 pthread_self()

线程创建 pthread_create(线程id指针 , NULL, 函数指针, 函数参数)

2.1 线程的并发

创建一个线程,让主进程和这个线程并发执行:

#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

void* handle(void*){
   
        for(int i=0;i<10;++i){
   
                sleep(1);
                cout << pthread_self() << ":" << i << endl;
        }
        return NULL;
}

int main(){
   
        cout << getpid() << endl;             // pid
        cout << pthread_self() << endl;       // 线程标识

        pthread_t tid;
        pthread_create(&tid,NULL,handle,NULL);     // 创建一个线程,handle传指针并返回指针,是这个线程做的事

        // 主进程也做这个
        for(int i=0;i<10;++i){
   
                sleep(1);
                cout 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值