global static boolean pointer causes segmentation fault using pthread

Posted by asksw0rder on Stack Overflow See other posts from Stack Overflow or by asksw0rder
Published on 2010-06-06T01:19:16Z Indexed on 2010/06/06 1:22 UTC
Read the original article Hit count: 276

Filed under:
|
|
|

New to pthread programming, and stuck on this error when working on a C++&C mixed code.

What I have done is to call the c code in the thread created by the c++ code. There is a static boolean pointer used in the thread and should got free when the thread finishes. However I noticed that every time when the program processed into the c function, the value of the boolean pointer would be changed and the segmentation fault then happened due to the free().

Detail code is as follows:

static bool *is_center;

// omit other codes in between ...

void streamCluster( PStream* stream)
{
    // some code here ...
    while(1){
        // some code here ...
        is_center = (bool*)calloc(points.num,sizeof(bool));

        // start the parallel thread here.
        // the c code is invoked in this function.
        localSearch(&points,kmin, kmax,&kfinal); // parallel

        free(is_center);
    }

And the function using parallel is as follows (my c code is invoked in each thread):

void localSearch( Points* points, long kmin, long kmax, long* kfinal ) {
    pthread_barrier_t barrier;
    pthread_t* threads = new pthread_t[nproc];
    pkmedian_arg_t* arg = new pkmedian_arg_t[nproc];

    pthread_barrier_init(&barrier,NULL,nproc);

    for( int i = 0; i < nproc; i++ ) {
            arg[i].points = points;
            arg[i].kmin = kmin;
            arg[i].kmax = kmax;
            arg[i].pid = i;
            arg[i].kfinal = kfinal;
            arg[i].barrier = &barrier;

            pthread_create(threads+i,NULL,localSearchSub,(void*)&arg[i]);
    }

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

    delete[] threads;
    delete[] arg;
    pthread_barrier_destroy(&barrier);
}

Finally the function calling my c code:

void* localSearchSub(void* arg_) {
    // omit some initialize code...

    // my code
    begin_papi_thread(&eventSet);

    // Processing k-means, omit codes. 
    // is_center value will be updated correctly

    // my code
    end_papi_thread(&eventSet); // when jumping into this, error happens
    return NULL;
}

And from gdb, what I have got for the is_center is:

Breakpoint 2, localSearchSub (arg_=0x600000000000bc40) at streamcluster.cpp:1711
1711      end_papi_thread(&eventSet);
(gdb) s

Hardware watchpoint 1: is_center

Old value = (bool *) 0x600000000000bba0
New value = (bool *) 0xa93f3
0x400000000000d8d1 in localSearchSub (arg_=0x600000000000bc40) at streamcluster.cpp:1711
1711      end_papi_thread(&eventSet);

Any suggestions? Thanks in advance!

© Stack Overflow or respective owner

Related posts about c++

Related posts about global-variables