Question

Please edit the title if you know the actual problem behind this. I'm facing a very strange behavior with pointers in C.

Version 1 (What I want but the output is not what I expect):

void *partial_evolve(void * pars)
{
    evolve_pars *p = (evolve_pars*)pars;
    unsigned char *in = *p->grid_in;
    unsigned char *out = *p->grid_out;

    for (int t = 0; t < p->time_steps; ++t)
    {
       for (int y = 0; y < p->dim_y; ++y)
         for (int x = p->start_x; x < p->end_x; ++x)
           evolve(in, out, p->dim_x, p->dim_y, x, y);

       swap(&in, &out);
       pthread_barrier_wait(&barrier);
    }
}

Version 2 (The output is right but I have to use two waits which I do not want):

void *partial_evolve(void * pars)
{
    evolve_pars *p = (evolve_pars*)pars;

    for (int t = 0; t < p->time_steps; ++t)
    {
       for (int y = 0; y < p->dim_y; ++y)
         for (int x = p->start_x; x < p->end_x; ++x)
           evolve(*p->grid_in, *p->grid_out, p->dim_x, p->dim_y, x, y);

       pthread_barrier_wait(&barrier);
       swap(p->grid_in, p->grid_out);
       pthread_barrier_wait(&barrier);
    }
}

The input struct that I use is:

typedef struct
{
    unsigned int dim_x;
    unsigned int dim_y;
    unsigned char **grid_in;
    unsigned char **grid_out;
    unsigned int start_x;
    unsigned int end_x;
    unsigned int time_steps;
    int is_master_thread;
} evolve_pars;

The swap function:

void swap(unsigned char **a, unsigned char **b)
{
    unsigned char *tmp = *a;
    *a = *b;
    *b = tmp;
}

Regardless of the rest of the code, the pointer operation of the partial_evolve function in both cases should behave the same. Any ideas?

Was it helpful?

Solution

In the first version, the swap() function is called with the address of 2 local pointers.

swap(&in, &out);

In the second version, the parameters are part of the structure

swap(p->grid_in, p->grid_out);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top