pthread_create

<aside> 💡 pthread_create 为调用进程创建一个子线程

</aside>

一般情况,main函数所在的线程称之为主线程/main线程。其余创建的线程称之为子线程

Untitled

参数

返回值

例子

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

void * callback(void * arg) {
    printf("child thread...\\n");
    printf("arg value: %d\\n", *(int *)arg);
    return NULL;
}

int main() {

    pthread_t tid;

    int num = 10;

    // 创建一个子线程
    int ret = pthread_create(&tid, NULL, callback, (void *)&num);

    if(ret != 0) {
        char * errstr = strerror(ret);
        printf("error : %s\\n", errstr);
    } 

    // 主线程执行的内容
    for(int i = 0; i < 5; i++) {
        printf("%d\\n", i);
    }
    // 让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
    // 防止子线程还没创建好主线程就exit了
    pthread_exit(NULL);

    return 0;   // exit(0);
}

pthread_self

<aside> 💡 pthread_self 用于获取当前线程的线程ID

</aside>

Untitled

pthread_exit

<aside> 💡 pthread_exit 用于终止一个线程,在哪个线程中调用就终止哪个线程

</aside>

Untitled