学习笔记7+代码

发布时间 2023-10-28 22:16:07作者: 20211423袁艺

一、苏格拉底挑战









二、遇见的问题




三、实践和代码


代码:
#include <stdio.h>
#include <pthread.h>

// 线程函数,接受一个void*参数,返回一个void*指针
void* thread_function(void* arg) {
    int thread_arg = *((int*)arg);
    printf("Thread received argument: %d\n", thread_arg);
    // 在这里可以添加线程的逻辑
    return NULL;
}

int main() {
    pthread_t thread_id;
    int data = 42;

    int result = pthread_create(&thread_id, NULL, thread_function, (void*)&data);
    if (result != 0) {
        perror("Thread creation failed");
        return 1;
    }

    // 可选择性等待线程结束
    result = pthread_join(thread_id, NULL);
    if (result != 0) {
        perror("Thread join failed");
        return 1;
    }

    printf("Main thread exiting.\n");
    return 0;
}

编译:

gcc test.c -lpthread -o test