gpt4 book ai didi

c - 带互斥同步的 Pi 计算器

转载 作者:行者123 更新时间:2023-11-30 19:42:46 24 4
gpt4 key购买 nike

在这里完成作业。使代码可以工作并计算饼图,但随机值除外,我收到以下错误:

  1. ./piesync 10 3在 3 个线程中使用 10 个项计算的 pi 为 3.14183961892940200045* `./piesync' 中的错误:free():下一个尺寸无效(快速):0x0000000001ca3010 *

  2. ./piesync 100 5* `./piesync' 中的错误:双重释放或损坏(输出):0x0000000000ee5040 *

我知道这可能与数组或互斥体有关,但无法弄清楚是什么。

代码:

//Pini Vaknine
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

//global variables
int N, T;
double gpie = 3.0;
pthread_mutex_t mutex;

//pie function
void* pie_runner(void* arg)
{
long j = (long)arg;
long lower = (N/T)*(j-1)+1;
long upper = ((N/T)*(j));
double myPartialSum = 0;
//printf("lower=%lu upper=%lu\n",lower , upper);

for(long i = lower; i <= upper; i++)
{
if(i % 2 == 0){
myPartialSum -= 4.0/((2*i)*(2*i+1)*(2*i+2));
//printf("vsum %lu = %f\n", j, vsum[j]);
}
else{
myPartialSum += 4.0/((2*i)*(2*i+1)*(2*i+2));
//printf("vsum %lu = %f\n", j, vsum[j]);
}


}
pthread_mutex_lock (&mutex);
gpie = gpie + myPartialSum;
pthread_mutex_unlock (&mutex);

pthread_exit(0);
//return NULL;
}

int main(int argc, char **argv)
{

if(argc != 3) {
printf("Error: Must send it 2 parameters, you sent %d\n", argc-1);
exit(1);
}
N = atoi(argv[1]);
T = atoi(argv[2]);


if(N <= T) {
printf("Error: Number of terms must be greater then number of threads.\n");
exit(1);
}



//launch threads
pthread_attr_t attr;
pthread_t *tids = (pthread_t *) calloc(T, sizeof(pthread_t));
if(tids == NULL) {
fprintf(stderr, "Memory allocation problem\n");
exit(1);
}


pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

for(long i = 1; i<=T; i++)
{

int r = pthread_create(&tids[i], &attr, pie_runner, (void*)i);
if(r<0) {
printf("ERROR: pthread_create() returned %d\n", r);
exit(2);
}
}

//wait for threads...
for(int k = 1; k<=T; k++)
{
pthread_join(tids[k], NULL);
}


printf("pi computed with %d terms in %d threads is %.20f\n", N, T, gpie);

pthread_mutex_destroy(&mutex);
pthread_attr_destroy(&attr);

free(tids);

return 0;
}

最佳答案

您的索引超出了数组的范围。您已在此处为 T 元素分配了一个数组

pthread_t *tids = (pthread_t *) calloc(T, sizeof(pthread_t));

但你在这里索引错误

for(int k = 1; k<=T; k++)
{
pthread_join(tids[k], NULL);
}

还有其他实例。在 C 中,您从 0 索引一个数组,因此循环应该是

for(int k=0; k<T; k++)

关于c - 带互斥同步的 Pi 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922783/

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