多线程编程--多线程的操作

多线程的操作


线程的操作主要分为三种:创建线程终止线程回收线程


创建线程


线程的创建函数如下:

在这里插入图片描述

样例1:创建两个线程,实现每隔 1s 打印一次信息

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

void *myThread1(void)
{
    for(int i = 0 ; i < 100; i++) {
        printf("%s: %d: This is the 1st pthread\n", __FILE__, __LINE__);
        sleep(1);
    }
    return NULL;
}

void *myThread(void)
{
    for(int i  = 0; i < 100; i++) {
        printf("%s: %d: This is the 2st pthread\n", __FILE__, __LINE__);
        sleep(1);
    }
    return NULL;
}

int main()
{
    int i = 0, ret = 0;
    pthread_t pid1, pid2;
    
    /*创建线程1*/
    ret = pthread_create(&pid1, NULL, (void*)myThread1, NULL);
    if(ret) {
        printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
        return 1;
    }

    /*创建线程2*/
    ret = pthread_create(&pid2, NULL, (void*)myThread2, NULL);
    if(ret) {
        printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
        return 1;
    }

    pthread_join(id1, NULL);
    pthread_join(id2, NULL);

    return 0;
}

例子2:创建一个线程实现参数传递

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

void *myThread(void *arg)
{
    int *num;
    num = (int *)arg;
    printf("%s: %d: create parameter is %d\n", __FILE__, __LINE__, *num);
    return (void *)0;
}

int main()
{
    pthread_t pid;
    int error;
    int test = 4;
    int *attr = &test;
    
    /*创建线程1*/
    error = pthread_create(&pid, NULL, (void*)myThread, (void *)attr);
    if(error) {
        printf("%s: %d: Create pthread error\n", __FILE__, __LINE__);
        return 1;
    }

    pthread_join(pid, NULL);
    return 0;
}

终止线程


终止线程有三种方式:

  • 线程从执行函数返回,返回值就是线程的退出码;
  • 线程被同一进程内的其他线程取消;
  • 线程调用 pthread_exit() 函数退出;

在这里插入图片描述

  • 如果线程是 分离线程,调用上述函数,线程资源会被系统回收,线程终止;
  • 如果线程是 结合线程,调用上述函数,会释放线程资源,但是不会释放线程号,线程号直到主线程 pthread_join 返回后才释放;

注意:

  • 如果主线程从 main() 调用返回时或调用 exit() 时,整个进程内的所有线程都会终止。
  • 如果是主线程调用了 pthread_exit,则仅仅只是主线程本身终止,同一进程内的其他线程不受影响;

回收线程


回收线程函数如下:

在这里插入图片描述

注意:

  • 回收线程函数只针对结合线程,它会阻塞当前线程,用以回收其他线程的线程号。
  • 如果多个线程等待同一线程终止,则所有等待线程将一直等待目标线程终止;然后,一个等待线程成功返回,其余的等待线程将失败并返回 ESRCH 错误。
  • 子线程要么设置为 分离状态,要么在主线程中使用 pthread_jion 回收子线程资源;
  • 主线程退出(main 函数运行到结尾),这个程序结束,所以主线程最好要使用 pthread_join 等待子线程运行结束;
  • 使用 pthread_join 的线程将会阻塞,直到子线程结束,pthread_join 函数返回;
  • 如果子线程使用 exit(),则可以结束整个进程;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值