线程的概述

#include <pthread.h>

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

    功能:创建一个子线程

    参数:

        -thread:传出参数,线程创建成功后,子线程的ID被写到该变量

        -attr:设置线程的属性,一般使用默认值NULL

        -start_routine:函数指针,这个函数是子线程需要处理的逻辑代码

        -arg:给第三个参数使用,传参

    返回值:成功:0

    失败:返回错误号

    获取错误号的信息:char* strerror(int errnum);

#include<pthread.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
void * callback(void * arg) {
    printf("child thread...");
    return NULL;
}
int main() {
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);
    if(ret != 0) {
        char* errstr = strerror(ret);
        printf("error: %s\n", errstr);
    }
    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }
    sleep(1);
    return 0;
}

#include <pthread.h>

    int pthread_join(pthread_t thread, void **retval);

    功能:和一个已经终止的线程进行连接,回收子线程的资源,这个函数是阻塞函数,调用一次只能回收一个子线程,一般在主线程中使用

    参数:

        -thread:线程ID

        -retval:接收子线程退出时的返回值

    Compile and link with -pthread.

#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
void* callback(void* arg) {
    printf("child thread id : %ld\n", pthread_self());
    sleep(3);
    return NULL;
}
int main() {
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);
    if(ret != 0) {
        char* errstr = strerror(ret);
        printf("errnum: %s\n", errstr);
    }
    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }
    ret = pthread_join(tid, NULL);
    if(ret != 0) {
        char* errstr = strerror(ret);
        printf("errnum: %s\n", errstr);
    }
    printf("回收子线程资源成功!\n");
    pthread_exit(NULL);//让主线程退出,对其他线程没有影响
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值