面试题答案
一键面试实现步骤:
- 包含必要的头文件,如
<pthread.h>
用于线程相关操作,<stdio.h>
用于输入输出,<stdlib.h>
用于标准库函数。 - 定义线程函数,其参数类型为
void *
,在函数内部将void *
类型的参数转换回int
类型。 - 在主线程中定义一个
int
类型的变量作为要传递给线程的参数。 - 使用
pthread_create
函数创建线程,并将参数的地址作为第四个参数传递进去。 - 使用
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 *)¶m) != 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
。