我需要帮助从线程返回整数值。我已经尝试了几件事,但无法让它工作。我是 C 新手,是的,这是家庭作业,但我被困住了,需要一些帮助。我已经在线程中创建了指针,但是当我将它传递回 main 时,它没有显示正确的值。我已经尝试过 malloc ,但这也不起作用。任何提示将不胜感激。
这是代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<pthread.h>
#include "FindNextHigher.h"
#include "SortNumber.h"
void *thread_next(void *arg)
{
/* Call FindNextHigher */
int *num =(int *)arg;
int next = FindNextHigher(*num);
printf("next= %d\n", next);
/* Convert int to pointer to pass and print to check*/
int *next_ptr=&next;
printf("nextptr= %d\n", *next_ptr);
return (void *)next_ptr;
}
int main(int argc, char *argv[])
{
FILE* f = fopen(argv[1], "r");
int i, num, *next_ptr;
printf("next_ptr = %d\n", *next_ptr);
pthread_t thread1, thread2, thread3, thread4;
void *exit_status;
for(i=1; i<=20; i++)
{
fscanf(f, "%d", &num);
if (i==1 || i<=60){
pthread_create(&thread1, NULL, thread_next, &num);
pthread_join(thread1, &exit_status);
printf("Threadid 1 processes number %d which is %d and the next higher number is %d\n", i, num, *next_ptr);
if (i==60){
printf("--------------Process finished for Thread 1----------");
}
}
else {
if (i==61 || i<=120){
pthread_create(&thread2, NULL, thread_next, &num);
pthread_join(thread2, &exit_status);
printf("Threadid 2 processes number %d which is %d and the next higher number is %d\n", i, num, *next_ptr);
if (i==120){
printf("--------------Process finished for Thread 2----------");
}
}
else{
if (i==121 || i<=180){
pthread_create(&thread3, NULL, thread_next, &num);
pthread_join(thread3, &exit_status);
printf("Threadid 3 processes number %d which is %d and the next higher number is %d\n", i, num, *next_ptr);
if (i==180){
printf("--------------Process finished for Thread 3----------");
}
}
else{
if (i==181 || i<=240){
pthread_create(&thread4, NULL, thread_next, &num);
pthread_join(thread4, &exit_status);
printf("Threadid 4 processes number %d which is %d and the next higher number is %d\n", i, num, *next_ptr);
if (i==240){
printf("--------------Process finished for Thread 4----------");
}
}
}
}
}
}
return 0;
}