c - 从线程返回单个整数值

标签 c pthreads return pthread-join

我需要帮助从线程返回整数值。我已经尝试了几件事,但无法正常工作。我是 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;
}

最佳答案

有一些错误。首先,您在打印之前不初始化 next_ptr

接下来,您在 4 个线程之间共享一个指向同一个变量实例的指针,没有任何同步机制来保护对它的访问。您将需要使用临界区或互斥/信号量。

关于c - 从线程返回单个整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15505037/

相关文章:

javascript - 使用 Ext.Ajax.request 使 ExtJS 单例返回对象

c - 负移位计数左移

c - 链表中的节点交换

c++ - 如何写入为结构保留的内存位置

c++ - 简单的线程! C++

java - 简单的return语句错误

c - Segmentation Fault 错误由于添加了一个小的 2d 数组

c - gdb 没有正确打印字符串值

在 c 中使用线程的 Curl 客户端会产生随机行为吗?

c++ - 取消引用不返回的函数时会发生什么?