linux的基础知识——线程

1.什么是线程?

在这里插入图片描述

2.linux内核线程实现原理

在这里插入图片描述在这里插入图片描述

3.线程共享资源

在这里插入图片描述

4.线程的非共享资源

在这里插入图片描述

5.线程优缺点

在这里插入图片描述

6.线程的控制原语

6.1 pthread_self函数

在这里插入图片描述

6.2 pthread_create函数

在这里插入图片描述在这里插入图片描述

6.3 程序:创建线程
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

void *thrd_func(void *arg)
{
    
    
        printf("子进程ID:%u;子线程ID:%lu\n",getpid(),pthread_self());
}
int main()
{
    
    
        pthread_t tid;
        int ret;

        printf("主进程ID:%u;主线程ID:%lu\n",getpid(),pthread_self());
        ret = pthread_create(&tid,NULL,thrd_func,NULL);
        if(ret != 0){
    
    
                printf("pthread_create error\n");
                exit(1);
        }
        sleep(1);
        return 0;
}

7.线程与共享

在这里插入图片描述

8.pthread_exit线程退出函数

在这里插入图片描述

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

void *tfn(void *arg)
{
    
    
        int i;
        i = (int)arg;
        printf("i am %dth thread,thread_id:%lu\n",i+1,pthread_self());
        return NULL;
}

int main()
{
    
    
        int n=5,i;
        pthread_t tid;

        for(i=0;i<n;i++){
    
    
                pthread_create(&tid,NULL,tfn,(void *)i);
        }
        printf("i am main thread,thread id:%lu\n",pthread_self());

        pthread_exit(NULL);
}

猜你喜欢

转载自blog.csdn.net/zxr916/article/details/111957345