我需要從線程返回整數值的幫助。我嘗試過幾件事情,但無法實現它的功能。我是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;
}
OT:怎麼樣使用'else if'或'switch'。至少可以節省縮進和大括號。 – alk 2013-03-19 19:07:39