我尝试在 osx 和 linux ubuntu 的终端中运行这段代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int fact=1; //this data is shared by thread(s)
int n;
int x;
int *arrayName;
int main(int argc, char *argv[])
{
if (argc != 3){ //check number of arguments
printf("Must use: a.out <integer value>\n");
return -1;
}
int x = atoi(argv[1]);
n = atoi(argv[2]);
if (n < 0){ //check second passed argument
printf("%d Must be >=0\n", atoi(argv[2]));
return -1;
}
arrayName = (int *) malloc(n * sizeof(int));
pthread_t tid[n];
for(int i=0;i<n;i++){
pthread_create(&tid[i], NULL, (void *) i, NULL);
}
int i=0;
while(i<n){
pthread_join(tid[i],NULL);
i++;
}
i=0;
while (i<n) {
printf("Thread is %d",arrayName[i]);
i++;
}
}
void *calculateMult(void *i) {
int j = (int) i;
arrayName[j] = x * j;
return NULL;
};
我在终端中运行了这些命令:
cc -pthread main.c
./a.out 1 1
但它给了我段错误:osx 中的 11 和 linux 中的段错误(核心转储), 为什么??
最佳答案
我认为你需要改变pthread_create调用,因为您在 pthread_create
中传递了错误的参数。还要检查 pthread_create
的返回值。
你需要这样的东西
int s = pthread_create(&tid[i], NULL, (void *)calculateMult, (void *)&i);
if (s != 0)
printf("pthread_create failed");
您还需要将函数更改为:
void *calculateMult(void *i) {
int *j = (int*) i;
arrayName[*j] = x * (*j);
return NULL;
};
这样你就完成了。
关于数组段错误中的 c 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40839751/