0

好的,我的程序碰壁了。我正在使用 pthreads 来实现一个并行程序,但是我遇到了这个块的“分段错误”。

//This is all in the main function
//{{{{{
//Creates the array that holds pointers to bodies
Body **bodies = new Body*[NUMBER_OF_BODIES];

int bodiesperthread = NUMBER_OF_BODIES / NUMBER_OF_THREADS;

//Creates an array to hold the pthreads
pthread_t threads[NUMBER_OF_THREADS];

//Here I partition the array of bodies to each thread
for(int j = 0; j < NUMBER_OF_THREADS; j++)
                {
                    if(j == (NUMBER_OF_THREADS - 1))
                    {
                        //Create a new array to hold some bodies
                        Body **subbodies = new Body*[bodiesremaining];

                        // Insert the bodies into the new sub array.
                        for(int i = nextindex; i < bodiesremaining; i++)
                            subbodies[i] = bodies[i];

                        // Launch the thread given this sub array.
                        pthread_create(&threads[j], NULL, &Tree::updateHelp, (void*)subbodies);
                    }
                    else
                    {
                        // If this is not the last thread we create the sub array with length equal to the
                        // bodies per thread. Then we update bodies remaining.
                        Body **subbodies = new Body*[bodiesperthread];
                        bodiesremaining -= bodiesperthread;

                        // Populate the new array.
                        for(int i = nextindex; i < bodiesperthread; i++)
                            subbodies[i] = bodies[i];

                        nextindex += bodiesperthread + 1;

                        // Launch the thread given the sub array.
                        pthread_create(&threads[j], NULL, &Tree::updateHelp, (void*)subbodies);
                    }
                }

                for(int i = 0; i < NUMBER_OF_THREADS; i++)
                    pthread_join(threads[i], NULL);
       //}}}}




//This is in Tree.cpp

void* Tree::updateHelp(void *bodies)
{
long tid = pthread_self();
Body **subbodies = (Body**)bodies;

//According to the CodeBlocks debugger the fault is occuring here
cout << "Thread " << tid << " has a body at (" << subbodies[0]->x << "," << subbodies[0]->y << ") with mass = " << subbodies[0]->mass << ".\n";
pthread_exit(NULL);
}

我对 C++ 非常熟悉,我一生都无法弄清楚为什么会出现此错误。是因为我必须 malloc 线程吗?它与所有的身体指针有关吗?我应该为子数组创建新的实体吗?

提前感谢您的帮助!

4

0 回答 0