MST

星途 面试题库

面试题:C语言中Linux线程创建时如何传递简单数据类型参数

在Linux环境下使用C语言创建线程,若要向线程函数传递一个int类型的参数,简述具体实现步骤并给出代码示例。
33.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

实现步骤:

  1. 包含必要的头文件,如<pthread.h>用于线程相关操作,<stdio.h>用于输入输出,<stdlib.h>用于标准库函数。
  2. 定义线程函数,其参数类型为void *,在函数内部将void *类型的参数转换回int类型。
  3. 在主线程中定义一个int类型的变量作为要传递给线程的参数。
  4. 使用pthread_create函数创建线程,并将参数的地址作为第四个参数传递进去。
  5. 使用pthread_join函数等待线程结束。

代码示例:

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

// 线程函数
void *thread_function(void *arg) {
    int num = *((int *)arg);
    printf("线程接收到的参数为: %d\n", num);
    pthread_exit(NULL);
}

int main() {
    pthread_t thread;
    int param = 42; // 要传递的int类型参数

    // 创建线程
    if (pthread_create(&thread, NULL, thread_function, (void *)&param) != 0) {
        perror("pthread_create");
        return 1;
    }

    // 等待线程结束
    if (pthread_join(thread, NULL) != 0) {
        perror("pthread_join");
        return 2;
    }

    printf("主线程等待线程完成\n");
    return 0;
}

注意:编译时需要链接pthread库,例如:gcc -o test test.c -lpthread