簡體   English   中英

基本使用線程進行分段錯誤

[英]Segmentation fault using threads in an elementary way

我正在使用pthreads做一個非常簡單的程序,但是我不斷收到“段錯誤”錯誤,我不明白為什么。 該程序將用C語言編譯。

該程序應創建3個線程,每個線程應打印其編號和調用線程的編號(在這種情況下,我只希望3個線程說“我是線程(i),調用線程為0”,因為它們都是從同一線程創建)

我認為問題在於用於分配要傳遞的內存的malloc函數。

如果這是個問題,我該如何解決?

我是否應該在“ for”循環之前創建一個由3個指針組成的數組,並將要傳遞給線程的兩個變量存儲在該數組的每個指針中? 實際如何做? 我嘗試過,但似乎沒有用。

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

void *Son (void* arg)
{int *id=(int*)arg; //retrieve array
  sleep(id[1]+1);
  printf("I'm thread %d , created from %d! \n",id[1],id[0]);

free(arg);
 pthread_exit(0);
}




int main()
{pthread_t threads[3];
 int i;
 for (i=0;i<3;i++)
    {int *a= malloc(2*sizeof(int)); // dynamically allocate a variable which will be freed in the thread once executed
    a[0]=0;  //store i in the content of dynamically allocated a
    a[1]=i;
    pthread_create(&threads[i],NULL,Son ,(void*)a);
    }
int j;
for (j=0;j<3;i++)
    {pthread_join(threads[i],NULL);
    printf("Joined thread %d",j);
    }
printf("THREAD FINISHED\n");
return 0;
}

這里:

for (j=0;j<3;i++)
{
    pthread_join(threads[i],NULL);
    printf("Joined thread %d",j);
}

您可能想使用threads[j]而不是threads[i] i ,此時為4,您正在通過pthread_join訪問無效的內存地址。 另外,您需要使用j++而不是i++

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM