【问题标题】:Segmentation fault creating threads分段错误创建线程
【发布时间】:2017-03-17 15:59:07
【问题描述】:

我必须使用线程来解决给定的问题,我唯一需要做的就是以某种方式使我的线程使用一个名为 launchR 的函数,我使用没有线程的函数测试了我的函数并且运行正常,但是每当我尝试弄乱线程我得到分段错误,我找不到原因。 这就是我处理线程的方式:

pthread_t threads[n];
    int rc, t;
    int *tid[n];

    int bpt  = b/n,
        macc = b%n,
        adv  = 0;
    for (t=0; t < n; t++) {
       tid[t] = (int *)malloc(sizeof(int));
       *tid[t]  = t;

       printf("Creando el Hilo %d\n",t);
       if (macc == 0 ) {
           rc = pthread_create(&threads[t],NULL,launchR(objarr,bombs,adv,obj,bpt), (void *)tid[t]);
           printf("\n Cree el Hilo THID: %d \n",*(tid[t]));
           if (rc) {
              printf("Error, %d\n",rc);
              exit(-1);
            }
           adv=adv+bpt;
       }
       else if (macc > 0 ) {
           rc = pthread_create(&threads[t],NULL,launchR(objarr,bombs,adv,obj,bpt+1), (void *)tid[t]);
           printf("\n Cree el Hilo THID: %d \n",*(tid[t]));
           if (rc) {
              printf("Error, %d\n",rc);
              exit(-1);
           }

           adv=adv+bpt+1;
           printf("%d\n", adv);
       }
       macc--;
    }

    for (t=0; t < n; t++) {
        pthread_join(threads[t],NULL);
    }

如果您能给我任何建议,我将不胜感激。

编辑:这是函数启动的代码,它基于另一个函数。

void launch ( int obj[][5] , int bombs[][4] , int bomb, int objs ) {
for (int i = 0; i < objs; ++i) {
    if ( obj[i][0] <= (bombs[bomb][0] + bombs[bomb][2]) && 
        obj[i][0] >= (bombs[bomb][0] - bombs[bomb][2]) &&
        obj[i][1] <= (bombs[bomb][1] + bombs[bomb][2]) && 
        obj[i][1] >= (bombs[bomb][1] - bombs[bomb][2])){

        if (obj[i][3] == 1) {
            obj[i][2] = obj[i][2] - bombs[bomb][2];
            obj[i][4] = 1;
        }

        else if (obj[i][3] == -1){
            obj[i][2] = obj[i][2] + bombs[bomb][2];
            obj[i][4] = 1;
        }
    }
}
}




void *launchR(int obj[][5] , int bombs[][4] , int ibomb, int objs, int cant){

for (int i = ibomb; i <= cant; i++) {
    launch(obj,bombs,i,objs);
}

}

编辑 2:这是我的输出:

entro en threads
Creando el Hilo 0

 Cree el Hilo THID: 0 
2
Creando el Hilo 1
[1]    19677 segmentation fault  ./batalla -t -n 3 prueba

【问题讨论】:

  • 你的编译器对rc = pthread_create(&amp;threads[t],NULL,launchR(objarr,bombs,adv,obj,bpt), (void *)tid[t]); 有什么看法(这几乎肯定是不正确的,编译器可能有义务警告你)。
  • 当我编译它时它什么也没说,甚至没有警告。为什么会不正确?
  • 因为我发现launchR() 不太可能返回void *(*)(void*)。如果我的怀疑是正确的(并且您正确地#included &lt;pthread.h&gt;)那么编译器必须发出诊断消息以将不正确的类型传递给pthread_create()
  • 我的代码是基于这个stackoverflow.com/questions/1662909/… ,还有launchR代码,我最近编辑了我的问题,供有人询问并删除了他的评论。

标签: c segmentation-fault pthreads


【解决方案1】:

函数声明是 无效发射(int obj[][5]、int 炸弹[][4]、int 炸弹、int objs); 因此 pthread_create 调用中的参数应该是函数启动的地址。 pthread_create 应该是:

pthread_create(&threads[t],NULL,(void *)&launchR(objarr,bombs,adv,obj,bpt+1), (void *)tid[t]); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2021-08-08
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多