初识pthread

141 阅读1分钟
//
//  main.c
//  POSIX Threads Playground for SQI
//
//  Created by 侯仕奇 on 2022/4/20.
//

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

void *start(char *param) {
    printf("%s, running the background thread which address is %p.\n", param, pthread_self());
    // 分配内存
    double *ret = (double *)malloc(sizeof(double));
    *ret = 3.1415926;
    return (void *)ret;
}

int main(int argc, const char * argv[]) {
    printf("Thread(%p) named main is running.\n", pthread_self());
    pthread_t background;
    int ret = pthread_create(&background, NULL, (void *)start, "hello pthread");
    if (ret != 0) {
        printf("Failed to create background thread.\n");
    }
    void *result = NULL;
    pthread_join(background, &result);
    printf("Background thread function result is %lf.\n", *(double *)result);
    // 释放内存
    free(result);
    printf("main thread exit.\n");
    return 0;
}