linux 线程学习初步01

  1. 线程的概念
    在这里插入图片描述
    进程与线程内核实现 通过函数clone实现的
ps -Lf pid
  1. Linux内核线程实现原理
    在这里插入图片描述
    同一个进程下的线程,共享该进程的内存区, 但是只有stack区域不共享。

  2. 线程共享资源
    a.文件描述符表
    b.每种信号的处理方式
    c.当前工作目录
    d.用户id和组id

  3. 线程非共享资源
    a.线程id
    b.处理器现场和栈指针(内核栈)
    c.独立的栈空间(用户空间栈)
    d.errno变量
    e.信号屏蔽字
    f.调度优先级

  4. 在主线程里面执行return, 相当于整个进程退出了

  5. 小技巧
    set -o vi 相当于把当前shell,弄成了 vi 编辑器模式

7.创建一个线程
man pthread_create

 #include <pthread.h>
 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
 void *(*start_routine) (void *), void *arg);
 Compile and link with -pthread.

在这里插入图片描述

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

void* func(void *arg) {
    printf("I am a common thread, pid is %d, tid is %ld\n", getpid(), pthread_self());
    pthread_exit(NULL);
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, func, NULL);
    printf("I am a man thread, pid is %d,create tid is %ld\n", getpid(), tid);
    printf("I am a man thread, pid is %d, tid is %ld\n", getpid(), pthread_self());
    
    pthread_exit(NULL);
    return 0;
}

经测试,主线程使用pthread_exit函数,可以等待子线程的退出。

线程退出函数:
在这里插入图片描述
8.线程回收函数:

int pthread_join(pthread_t thread, void **retval);
参数介绍:
	thread: 表示要回收的线程(创建线程时候传出的第一个参数)
	retval:要回收的线程的退出信息

线程回收也是阻塞等待回收
代码案例:

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

void* func(void *arg) {
    printf("I am a common thread, pid is %d, tid is %ld\n", getpid(), pthread_self());
    // pthread_exit((void *)100);
    return (void*)(100);
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, func, NULL);
    printf("I am a man thread, pid is %d,create tid is %ld\n", getpid(), tid);
    printf("I am a man thread, pid is %d, tid is %ld\n", getpid(), pthread_self());
    void * ret;
    pthread_join((tid), &ret);
    printf("join tid return value is %d\n", (int)ret);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值