Linux C++ uses pthread_create to create a thread example

Note: join will block the main thread

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

void* thread_function(void* arg) {
    // 子线程要执行的代码
    printf("子线程执行中...\n");

    // 结束当前子线程
    pthread_exit(NULL);
}

int main() {
    pthread_t thread_id;

    // 创建子线程
    int ret = pthread_create(&thread_id, NULL, thread_function, NULL);
    if (ret != 0) {
        printf("创建线程失败\n");
        return 1;
    }

    // 设置子线程为分离态
    pthread_detach(thread_id);

    // 主线程继续执行其他任务
    printf("主线程继续执行...\n");

    // 等待一段时间,以防止程序立即退出
    sleep(1);
  
    return 0;
}

Guess you like

Origin blog.csdn.net/wangningyu/article/details/132841752