c - C/Linux 中的多线程埃拉托斯特尼筛法

标签 c linux multithreading pthreads

我目前正在使用 C 多线程计算埃拉托斯特尼筛法。

目标是首先创建一个主线程,该主线程使用 split 函数来划分多个线程上的数字探索。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>

void *creat_thread(int *nbThreads);

void *SieveEratosthenes(int *tailleTab);

int* tab;
int sizeTab;
int nbTachesParThread=0;

int main(void)
{
  int nbThreads;
  int n;
  do{
    printf("Enter an integer > 1 :  ");
    scanf("%d", &n);
  } while(n<2);


  sizeTab = n+1;
  tab = (int*)malloc(tailleTab*sizeof(int));
  for (unsigned int i=0; i<tailleTab; i++)
  {
    tab[i] = 1;
  }

  do{
    printf("Enter a number positive number of threads : ");
    scanf("%d", &nbThreads);
  } while(nbThreads<1);

  pthread_t threadPrincipal;

  if (pthread_create(&threadPrincipal, NULL, creat_thread, NULL)) {
    perror("pthread_create");
    return EXIT_FAILURE;
  }

  if (pthread_join(threadPrincipal, NULL)) {
    perror("pthread_join");
    return EXIT_FAILURE;
  }

  printf("The Prime numbers are : \n");
  for(unsigned int i=0; i<sizeTab; i++)
  {
    if(tab[i]==1)
    {
      printf("%d\n", (i));
    }
  }


}

void *creat_thread(int *nbThreads)
{

  int nbTachesParThread = (int) sqrt(sizeTab) / nbThreads;
  pthread_t* threads = (pthread_t*)malloc(nbThreads*sizeof(pthread_t));

  int plageThreadi = nbTachesParThread;

  for(int i = 0; i < nbThreads; ++i)
    pthread_create (&threads[i], NULL, SieveEratosthenes, plageThreadi);
    plageThreadi += nbTachesParThread;
}

void *SieveEratosthenes(int *plageThread)
{


  for( int i=(plageThread - nbTachesParThread); i<=plageThread; i++)
  {
    if (tab[i] == 1)
    {
      for (int j = i*i; j<sizeTab; j += i)
      {
        tab[j]=0;
      }
    }
  }

}


我尝试实现代码,但在运行时出现错误:

segmentation error (core dumped)  

最佳答案

除了 my comment here 中提到的问题之外还有更多需要修复的地方:

首先,PThread 函数的类型必须是 void *(*)(void*)。代码使用的类型为 void *(*)(int*)。不好。

第二,代码错过了加入工作线程,因此分配线程在创建所有工作线程后结束,然后它在 main() 中加入,然后访问工作线程最常访问的变量可能仍在努力引起未定义的行为,然后结束,结束该过程。结束进程会取消所有工作线程。

关于c - C/Linux 中的多线程埃拉托斯特尼筛法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523757/

相关文章:

c - 在 c 的终端中没有出现预期的输出

c++ - 在 Linux 上的 QT 应用程序中识别控件名称/ID

c - 在 C 中使用 HTTP POST 上传 JPEG

windows - windows线程溢出时如何查看当前栈大小

java - 线程同步行为

c++ - 你能在另一个线程中运行一个线程吗?

c - 更好地优化搜索字符串的方式

c - 为什么 "typedef struct foo foo;"被认为是有害的?

c - 这对 getchar() 方法不起作用是什么?

sql-server - 索引超出范围 : JDBC SqlServer exception