LINUX中的线程管理相关函数

进程与线程

进程:系统分配资源的基本单位,它没有代码执行能力。

线程:进程内部的一条执行路线,它是系统分配CPU时间片的基本单位。

每一个线程都应一个线程函数,线程创建成功后会调用线程函数,线程函数一旦返回,相应的线程就结束。

主函数可以认为是主线程的线程函数,主线程是由系统创建,也是最先被创建,只能有一个。而普通线程是由主线程直接或者间接创造,可以没有也可以有一个或者多个。

主线程一旦结束,进程就随之结束,其他所有普通线程必须强制结束,儿,某一个普通线程结束不会对其他线程造成任何影响。

主线程和普通线程并发执行,没有特殊化!···

LINUX中的线程管理相关函数

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.
返回值:成功返回 0, 失败返回失败数字,并且第一个参数不会设置
pthtea_t 这个是进程号,
pthread_attr_t 线程属性结构体,这个参数通常为 NULL
start_soutine  函数指针 传递进程函数名
arg 进程函数参数

pthread_exit函数:退出当前线程

void pthread_exit(void *retval);

pthread_join函数:以阻塞方式等待某一线程结束。

int pthread_join(pthread_t thread, void **retval);
参数pthread_t 线程号 
    retval:  用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。
​

pthread_cancel函数:结束某个线程,只是请求取消运行

int pthread_cancel(pthread_t thread);
参数:
    进程号
返回值:
    成功返回 0  ,失败返回错误号

pthread_self函数: 获取当前线程的TID

 pthread_t pthread_self(void);
 返回值:
    进程TID

参考代码:

#include <stdio.h>
#include <pthread.h>
typedef struct student
{
    int id;
    char name[100];
}stu;
void* pth_handler(void* data)
{
    pthread_t tid;
    tid = pthread_self();
    unsigned int ID =(unsigned int)tid;
    pthread_t ttid = (pthread_t)data;
    int cnt = 0 ;
    while(1)
    {
        if(5 == cnt)
        {
            printf("\n\n线程1 进入阻塞,等待进程2 退出!\n\n");
            pthread_join(ttid, NULL);
        }
        if(10 == cnt)
        {
            printf("线程1退出\n");
            pthread_exit(NULL);
​
        }
        printf(" 1 号线程正在运行! TID = %u\n",ID);
        sleep(1);
        ++cnt;
​
    }
​
}
​
void* ptr_fun(void* data)
{
    pthread_t tid;
    //tid = pthread_self();
    int ID =(int)tid;
    stu* s = (stu*)data;
    int cnt=0;
    while(1)
    {
    
    //  printf("TID为 %d的进程正在运行!\n",ID);
        printf("学生信息:");
        printf("学号:%d  姓名:%s\n",s->id,s->name);
        sleep(1);
        ++cnt;
    }
}
​
int main(int argc, char const *argv[])
{
    stu s1 = {1001,"张三"};
    pthread_t tid1,tid2;
    int cnt = 0;
​
    if(pthread_create(&tid2, NULL, ptr_fun, (void*)&s1))
    {
        perror("线程 2 创建失败!");
    }
    if(pthread_create(&tid1, NULL, pth_handler, (void*)tid2))
    {
        perror("线程 1 创建失败!");
    }
​
    while(1)
    {
        if(5 == cnt)
        {
            pthread_cancel(tid2);
            printf("线程2退出\n");
​
        }
        if(10 ==cnt )
        {
            pthread_exit(NULL);
            printf("主线程退出\n");
        }
​
        printf("这是主线程!\n");
        sleep(3);
        ++cnt;
​
    }
    
​
​
    return 0;
}
​

猜你喜欢

转载自blog.csdn.net/qq_40839779/article/details/82820787
今日推荐