#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "jisuan.h" #include "shuru.h" #include "math.h" void *thread_func(void *thread_id); #define NUM_THREADS 2 int main(int argc, char *argv[]) { int rc; pthread_t threads[NUM_THREADS]; int ret; long t; shuru(); // for (t = 0; t < NUM_THREADS; t++) { printf("Creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, thread_func, (void *) t); if (rc) { printf("Error: return code from pthread_create() is %d\n", rc); exit(-1); } } for (t = 0; t < NUM_THREADS; t++) { pthread_join(threads[t], NULL); } pthread_exit(NULL); } void *thread_func(void *thread_id) { long tid; tid = (long) thread_id; printf("Thread %ld is running\n", tid); // if(tid == 0) { } if(tid == 1) { double h = 100.0; // 初始高度 double s = 0.0; // 总路程 // 计算落地路程 s = calculate_distance(h); // 输出结果 printf("第%d次落地时,球经过的总路程为:%.6f米\n", num, s); printf("第%d次反弹的高度为:%.6f米\n", num, h / pow(2, num)); } pthread_exit(NULL); }为什么不能正确传递参数num
时间: 2024-03-14 13:45:17 浏览: 236
在这段代码中,变量 num 没有被定义或初始化,所以在调用函数 calculate_distance() 和打印结果时会出现错误。要正确传递参数 num,需要在主函数中定义并初始化它,然后将它作为参数传递给 thread_func() 函数。例如:
int num = 10; // 初始化 num
pthread_create(&threads[t], NULL, thread_func, (void *) &num); // 将 num 的地址传递给线程函数
然后在 thread_func() 函数中需要使用指针来获取 num 的值,例如:
int *p_num = (int *) thread_id; // 将 thread_id 转换为 int 类型的指针
int num = *p_num; // 获取 num 的值
这样就可以在线程函数中正确使用 num 变量了。