线程不会在 C 中执行

Thread doesn't get executed in C

我正在尝试用 C 语言创建一个程序,通过 threads.It 的 university.The 练习来计算总和和乘积 我面临的问题是,当我 运行线程似乎没有编程 execute.I 卡住了,我不知道如何继续。

  #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);
   }

没用 either.the 无论如何我得到的输出是:

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

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

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

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

pthread_join(Th, NULL);

1) 您的 main() 线程没有等待线程完成。所以你的线程 Sum 可能根本不会执行。调用 pthread_join():

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

2) 您正在 main() 中再次声明和分配 array 。因此,分配仅针对 main() 中的 array,因为它 shadows the global variable. This leads to undefined behaviour 因为您在 Sum 线程中写入的 array 未分配任何内存。所以

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

应该是

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

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

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

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

并在线程函数中执行:

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