线程的概述

线程的概述_第1张图片线程的概述_第2张图片线程的概述_第3张图片

线程的概述_第4张图片线程的概述_第5张图片

#include

    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
#include
#include
#include
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

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

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

    参数:

        -thread:线程ID

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

    Compile and link with -pthread.

#include
#include
#include
#include
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;
}

你可能感兴趣的:(算法)