学习记录——day24 多线程编程

目录

多线程局部概念

线程支持函数(多线程编程)

pthread_create:创建线程

 pthread -self:线程号获取

pthread_exit:线程退出函数

pthread_jion:线程资源回收

pthred_detath:线程分离态

pthread_cancel:线程取消函数

pthread_sercancelstate:设置取消属性

多线程允许使用同一个线程体函数

作业


多线程局部概念

        1)线程:也称为轻量版的进程(LWP),是更小的任务执行单元,是进程的一个执行路径

        2)线程是任务器调度的最小单位

        3)个进程中可以包含多个线程,多个线程共享进程的资源

        4)线程几乎不占用资源,只是占用了很少的用于程序状态的资源(大概有8k左右)

        5)由于多个线程共同使用进程的资源,导致,线程在操作上容易出现不安全的状态

        6)线程操作开销较小、任务切换效率较高

        7)一个进程中,至少要包含一个线程(主线程)

        8)在有任务执行漫长的IO等待过程中,可以同时执行其他任务

        9)linux中不直接支持线程相关的支持库,需要引入第三方库,线程支持库

                sudo apt-get install manpages-posix manpages-posix-dev

                如果程序中使用的线程支持库中的函数,编译程序时,需要加上-pthread 选项

线程支持函数(多线程编程)

pthread_create:创建线程

       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
       功能:在当前进程中,创建一个分支线程
       参数1:用于接收创建好的线程ID
       参数2:线程的属性,一般填NULL表示使用系统默认的属性创建线程
       参数3:线程体函数,需要传递一个函数,参数为void*,返回值为void*
       参数4:参数3的参数
       返回值:成功创建返回0,失败返回一个错误码,注意,不是内核提供的错误码       
 

#include <myhead.h>

struct Buf
{
    int num;
    double key;
};

void *task(void *arg)
{
    int num = (*((struct Buf*)arg)).num;
    double key = ((struct Buf*)arg)->key;
    while (1)
    {
        printf("分支线程  num = %d,key = %.2lf\n",num,key);
        sleep(1);
    }
}

int main(int argc, char const *argv[])
{
    int num = 2024;
    double key = 1024;

    struct Buf buf = {num,key};

    pthread_t tid = 1;

    if (pthread_create(&tid, NULL, task, &buf) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx\n",tid);

    getchar();
    while (1);

    return 0;
}

 pthread -self:线程号获取

       #include <pthread.h>

       pthread_t pthread_self(void);
    功能:获取当前线程的线程号
    参数:无
    返回值:当前线程的线程号

pthread_exit:线程退出函数

       #include <pthread.h>

       void pthread_exit(void *retval);
    功能:退出当前的线程
    参数:线程退出时的状态,一般填NULL
    返回值:无

#include <myhead.h>

void *task(void *arg)
{
    printf("子线程线程号 = %#lx\n", pthread_self());
    
    //exit(EXIT_SUCCESS);  //再线程中进程退出  主线程也会结束
    pthread_exit(NULL);  //线程退出 不影响主线程
}

int main(int argc, char const *argv[])
{
    //定义变量存储线程号
    pthread_t tid = 1;

    //创建线程
    if (pthread_create(&tid, NULL, task, NULL) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx 线程号 = %#lx\n", tid, pthread_self());

    //阻塞函数  主线程结束进程结束,分支线程也终止
    getchar();

    return 0;
}

pthread_jion:线程资源回收

       #include <pthread.h>

       int pthread_join(pthread_t thread, void **retval);
    功能:阻塞等待给定线程的退出,并回收该线程的资源
    参数1:要回收的线程号
    参数2:接收线程退出时的状态
    返回值:成功返回0,失败返回错误码

#include <myhead.h>

void *task(void *arg)
{
    printf("子线程 线程号 = %#lx\n", pthread_self());
    
    sleep(3);
    //exit(EXIT_SUCCESS);  //再线程中进程退出  主线程也会结束
    pthread_exit(NULL);  //线程退出 不影响主线程
}

int main(int argc, char const *argv[])
{
    //定义变量存储线程号
    pthread_t tid = 1;

    //创建线程
    if (pthread_create(&tid, NULL, task, NULL) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx 线程号 = %#lx\n", tid, pthread_self());

    //阻塞回收分支线程的资源
    if(pthread_join(tid,NULL) == 0)
    {
        printf("成功回收%#lx的资源\n",tid);
    }

    //阻塞函数  主线程结束进程结束,分支线程也终止
    getchar();

    return 0;
}

pthred_detath:线程分离态

       #include <pthread.h>

       int pthread_detach(pthread_t thread);
    功能:将线程设置成分离态,设置了分离态的线程,退出后,由系统回收其资源
    参数:要被分离的线程id号
    返回值:成功返回0,失败返回错误码

#include <myhead.h>

void *task(void *arg)
{
    printf("子线程 线程号 = %#lx\n", pthread_self());
    
    sleep(3);
    //exit(EXIT_SUCCESS);  //再线程中进程退出  主线程也会结束
    pthread_exit(NULL);  //线程退出 不影响主线程
}

int main(int argc, char const *argv[])
{
    //定义变量存储线程号
    pthread_t tid = 1;

    //创建线程
    if (pthread_create(&tid, NULL, task, NULL) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx 线程号 = %#lx\n", tid, pthread_self());

    // //阻塞回收分支线程的资源
    // if(pthread_join(tid,NULL) == 0)
    // {
    //     printf("成功回收%#lx的资源\n",tid);
    // }

    //将线程设置成分离态
    pthread_detach(tid);
    printf("线程已退出\n");

    //阻塞函数  主线程结束进程结束,分支线程也终止
    getchar();

    return 0;
}

pthread_cancel:线程取消函数

#include <myhead.h>

void *task(void *arg)
{
    int n =0;
    while (1)
    {
        printf("子线程 线程号 = %#lx\n", pthread_self());
        n++;
        sleep(1);
        if (n == 10)
        {
            break;
        }
        
    }
    
    
    
    //exit(EXIT_SUCCESS);  //再线程中进程退出  主线程也会结束
    pthread_exit(NULL);  //线程退出 不影响主线程
}

int main(int argc, char const *argv[])
{
    //定义变量存储线程号
    pthread_t tid = 1;

    //创建线程
    if (pthread_create(&tid, NULL, task, NULL) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx 线程号 = %#lx\n", tid, pthread_self());

    // //阻塞回收分支线程的资源
    // if(pthread_join(tid,NULL) == 0)
    // {
    //     printf("成功回收%#lx的资源\n",tid);
    // }

    //将线程设置成分离态
    pthread_detach(tid);
   

    
    sleep(5);
    //向分支线程发送取消请求
    pthread_cancel(tid);
    printf("线程已退出\n");

    //阻塞函数  主线程结束进程结束,分支线程也终止
    getchar();

    return 0;
}

pthread_sercancelstate:设置取消属性

       #include <pthread.h>

       int pthread_setcancelstate(int state, int *oldstate);
    功能:设置是否接收取消指令
    参数1:新的状态
        PTHREAD_CANCEL_ENABLE:可接受状态
        PTHREAD_CANCEL_DISABLE:不可接收状态
    参数2:线程的旧的状态容器,如果不愿意要之前的状态,填NULL即可
    返回值:成功返回0,失败返回错误码

#include <myhead.h>

void *task(void *arg)
{
    //设置线程不可取消状态
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
    
    int n =0;
    while (1)
    {
        printf("子线程 线程号 = %#lx\n", pthread_self());
        n++;
        sleep(1);
        if (n == 10)
        {
            break;
        }
        
    }
    
    
    
    //exit(EXIT_SUCCESS);  //再线程中进程退出  主线程也会结束
    pthread_exit(NULL);  //线程退出 不影响主线程
}

int main(int argc, char const *argv[])
{
    //定义变量存储线程号
    pthread_t tid = 1;

    //创建线程
    if (pthread_create(&tid, NULL, task, NULL) != 0)
    {
        printf("pthread error");
        return -1;
    }

    printf("主线程 tid = %#lx 线程号 = %#lx\n", tid, pthread_self());

    // //阻塞回收分支线程的资源
    // if(pthread_join(tid,NULL) == 0)
    // {
    //     printf("成功回收%#lx的资源\n",tid);
    // }

    //将线程设置成分离态
    pthread_detach(tid);
    printf("线程已退出\n");

    
    sleep(5);
    //向分支线程发送取消请求
    pthread_cancel(tid);

    //阻塞函数  主线程结束进程结束,分支线程也终止
    getchar();

    return 0;
}

多线程允许使用同一个线程体函数

#include <myhead.h>

void *task(void *arg)
{
    if (strcmp((char*)arg,"hello") == 0)
    {
        int num = 10;
        while (num--)
        {
            printf("线程1\n");
            sleep(1);
        }
        pthread_exit(NULL);
    }
    else if (strcmp((char*)arg,"world") == 0)
    {
        sleep(5);
        printf("     线程2\n");
       
    }
    pthread_exit(NULL);

}

int main(int argc, char const *argv[])
{
    pthread_t tid1,tid2;

    if (pthread_create(&tid1,NULL,task,"hello") != 0)
    {
        printf("tid1 error");
        return -1;
    }

    if (pthread_create(&tid2,NULL,task,"world") != 0)
    {
        printf("tid2 error");
        return -1;
    }

    //阻塞等待线程结束
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);


    return 0;
}

作业

1、使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,1主线程回收两个分支线程的资源

#include <myhead.h>

// 定义结构体存储信息
struct Buf
{
    int len;
    int s;
    const char *o_file;
    const char *n_file;
};

// 拷贝函数
void copy_file(const char *srcfile, const char *destfile, int start, int len)
{
    // 以只读的形式打开源文件
    int sfd = open(srcfile, O_RDONLY);
    if (sfd == -1)
    {
        perror("open srcfile error");
        return;
    }

    // 以创建的形式打开目标文件
    int dfd = open(destfile, O_WRONLY);
    if (dfd == -1)
    {
        perror("open destfile error");
        return;
    }

    // 移动光标位置
    lseek(sfd, start, SEEK_SET);
    lseek(dfd, start, SEEK_SET);

    // 定义搬运工
    char buf[128] = "";
    int sum = 0; // 记录拷贝的总个数
    while (1)
    {
        // 从源文件中读取数据
        int res = read(sfd, buf, sizeof(buf));
        sum += res; // 将读取的个数累加

        if (res == 0 || sum > len) // 表示文件读取结束
        {
            write(dfd, buf, res - (sum - len)); // 父进程将最后一次拷贝结束
            break;
        }
        // 写入到目标文件中
        write(dfd, buf, res);
    }

    // 关闭文件
    close(sfd);
    close(dfd);

    printf("拷贝成功\n");
}

// 线程功能
void *task(void *arg)
{
    printf("线程开始\n");

    //读取数据
    int n = ((struct Buf *)arg)->len;
    int start = ((struct Buf *)arg)->s;
    printf("%d\n",start);
   
     //调用拷贝函数
    copy_file(((struct Buf *)arg)->o_file, ((struct Buf *)arg)->n_file, start, n);
    //线程退出
    pthread_exit(NULL);
}

int get_file_len(const char *o_file, const char *n_file)
{
    int ofd = open(o_file, O_RDONLY);
    if (ofd < 0)
    {
        perror("82ofd open error");
        exit(EXIT_SUCCESS);
    }

    umask(0000);

    int nfd = open(n_file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
    if (nfd < 0)
    {
        perror("89nfd open error");
        exit(EXIT_SUCCESS);
    }

    int len = lseek(ofd, 0, SEEK_END);

    close(ofd);
    close(nfd);

    return len;  
}

int main(int argc, char const *argv[])
{
    if (argc != 3)
    {
        printf("终端输入错误\n");
        return -1;
    }

    struct Buf buf1, buf2; // 定义信息传输结构体

    int res = get_file_len(argv[1], argv[2]);

    buf1.len = res / 2;
    buf1.o_file = argv[1];
    buf1.n_file = argv[2];
    buf1.s = 0;

    buf2.len = res - res / 2;
    buf2.o_file = argv[1];
    buf2.n_file = argv[2];
    buf2.s = res / 2;

    pthread_t tid1, tid2;

    if (pthread_create(&tid1, NULL, task, &buf1) != 0)
    {
        printf("tid1 error");
        return -1;
    }


    if (pthread_create(&tid2, NULL, task, &buf2) != 0)
    {
        printf("tid2 error");
        return -1;
    }

    // 将线程设置成分离态
    pthread_detach(tid1);
    pthread_detach(tid2);
    printf("线程已退出\n");

    // 阻塞等待线程结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("回收结束\n");
    getchar();

    return 0;
}

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值