线程不会在C中执行

时间:2015-12-17 20:28:06

标签: c multithreading pthreads

我正在尝试在C中创建一个程序,通过线程计算总和和产品。这是我的大学练习。我面临的问题是,当我运行程序时,线程不会似乎执行。我陷入困境,我不知道如何继续。

  #include <pthread.h>
  #include <stdio.h>
  #include <stdlib.h>
  int T1; //store the sum
  int *array; //global varriable

 void *Sum(void *N){ //function used by thread to calculate sum
     printf("I am the 1st thread i ll calculate the sum for you");
     long S=(long) N;
     int sum=0;
     int i;

     for (i=0; i<S; ++i){
       sum = sum +array[i];
     }  
     T1 = sum;
     pthread_exit(NULL);
}


int main(int argc, char *argv[])
{
  long N;
  printf("%d\n",T1);
  printf("give the size of the array please\n");
  scanf("%ld", &N);
  int *array= (int*) malloc((N)*sizeof(int)); // dynamic array
  int i;
  for (i=0; i<N; ++i)
  {
     array[i]=rand() % 301 + (-150);// creates random numbers from -150     to 150
  }
  for (i=0; i<N; ++i) {
    printf(" %d\n", array[i]);
  }

  pthread_t Th;
  pthread_create(&Th, NULL,Sum, (void*)N); //creates thread

  printf("%d\n",T1);
  return (0);
 }`    

我尝试将pthread_exit(NULL);更改为return(0)return(T1) 但它没有用。我将Sum函数更改为:

    void *Sum(void *N){ //function used by thread to calculate sum
      printf("I am the 1st thread i ll calculate the sum for you");
      pthread_exit(NULL);
   }

它也没有用。我得到的输出是:

0
give the size of the array please
2
 117
 113
0

请注意,我没有收到编译错误或警告。

2 个答案:

答案 0 :(得分:3)

1)你的main()线程没有等待线程完成。因此,您的线程 Sum 可能根本无法执行。致电pthread_join()

pthread_create(&Th, NULL,Sum, &N); 
pthread_join(Th, 0); // waits for the thread "Sum"

2)您在array中声明并再次分配main() 。因此,分配仅适用于array中的main(),因为它shadows是全局变量。这导致undefined behaviour,因为您在array线程中写入的Sum未分配任何内存。所以

  int *array= (int*) malloc((N)*sizeof(int)); // dynamic array

应该是

  array= malloc((N)*sizeof(int)); 

void*可以自动转换为任何其他对象指针。所以演员阵容是不必要的,可能是dangerous

3)指针转换的整数具有实现定义的行为。所以我会避免它。由于线程只读取N,因此您可以传递它的地址:

pthread_create(&Th, NULL,Sum, &N); //creates thread

并在线程函数中执行:

  long S=*((long*) N);

答案 1 :(得分:2)

pthread_create(&Th, NULL,Sum, (void*)N); //creates thread

在此行之后,您需要加入或分离该主题。在这种情况下,您将要加入该主题,否则您的程序将立即结束。

pthread_join(Th, NULL);
相关问题