gpt4 book ai didi

c - pthread_join 后的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:46 25 4
gpt4 key购买 nike

我正在尝试使用 c 在 ubuntu 中使用多个线程计算 pi 的值。我不太熟悉 pthread_create 和 pthread_join 应该作为输入获取的变量,以及如何处理“void”类型。我在代码中植入了一些 printf,以便找到问题的根源,显然问题出在 main() 中最后一个“for 循环”中的“pthread_join”

这是我的代码:

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

void* drawpoints (void* arg)
{
int i;
int* counter;
double x,y,dist; /*coordinates of point*/
int* n = arg;
*counter = 0;
srand(time(NULL));
for (i = 0; i<*n; i++)
{
/*square is of size 1X1 - 0<=x,y<=1 -> radius = 0.5*/
x = (double)rand()/(double)RAND_MAX;
y = (double)rand()/(double)RAND_MAX;
/*0.5 is the center of circle*/
dist = sqrt(pow(x-0.5,2)+pow(y-0.5,2));
if (dist<0.5)
{
*counter++;
}
/* printf("x = %f\ny = %f\ndist = %f\ncounter = %d\n\n",x,y,dist,*counter);*/
}
return (void*)counter;

}
int main (int argc, char** argv)
{
assert(argc == 3);

int rc;
int totalThreads,n,i,counter,numDots;
void* currPtr;
int* curr;
pthread_t* p_list = (pthread_t*)malloc(sizeof(pthread_t)*atoi(argv[2]));
n = atoi(argv[1]);
totalThreads = atoi(argv[2]);
numDots = n/totalThreads;
for (i = 0; i<totalThreads; i++)
{
rc = pthread_create(&(p_list[i]), NULL, drawpoints, &numDots); assert(rc == 0);
}
for (i = 0; i<totalThreads; i++)
{
printf("%lu\ntry\n\n",p_list[i]);
rc = pthread_join(p_list[i], &currPtr); assert(rc == 0);
curr = currPtr;
counter+=(*curr);
}
printf("%f\n\n",(double)counter/n*4);
free(p_list);
return 0;

这是我在终端中得到的日志:

3079416688
try

Segmentation fault

最佳答案

从你的函数 drawpoints:

int* counter; //You don't allocate memory for this int
double x,y,dist; /*coordinates of point*/
int* n = arg
*counter = 0; //yet here you assign 0 to a unknown memory location

所以在取消引用计数器之前,你必须运行这样的东西:

int* counter = malloc(sizeof(int));

并检查 couter != NULL 是否存在。

此外,您还需要确保在使用后也将其释放。

关于c - pthread_join 后的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com