启动新线程

多线程

#include <threads.h>

typedef struct {
    int a;
    int b;
    int result;
} AddTask;

//线程函数接受 void * 并返回 int
int add(void *arg) {
    AddTask *task = arg;
    task->result = task->a + task->b;
    return 0;
}

AddTask task = {3, 5, 0};
thrd_t thread;
if (thrd_create(&thread, add, &task) != thrd_success) {
    exit(EXIT_FAILURE);
}

//add 在一旁运行时,主线程继续执行
printf("main thread\n");

//main 结束就会连同所有线程一起结束程序,
//所以 main 要在结束前等待该线程
thrd_join(thread, nullptr);
//task.result is 8

printf("task.result is %d\n", task.result);