0

I have been implementing Strassen algorithm with threads. I have passed data to threads by structures and launching them by function pthread_create() . The problem is I'm operating on std::vector < std::vector<int> > and I can't pass this to structure by reference. I have done some research and decided to use std::ref to wrap content and send it to function. The problem begins after exiting the function; r1 value does not change (inside changes), so there is something incorrect.

Example code:

typedef struct threadData
{
    int n;
    std::vector< std::vector<int> > mat1;
    std::vector< std::vector<int> > mat2;
    std::vector< std::vector<int> > result;
}thread_Data;



/* function adding 2 matrixes */

void *add_Thread(void *arg)
{
    thread_Data *data = (threadData*)arg;
    for (int i = 0; i < data->n; ++i)
    {
        for (int j = 0; j < data->n; ++j)
        {
            data->result[i][j] = data->mat1[i][j] + data->mat2[i][j];
        }
    }

    pthread_exit(0);
}

/* ... code ... */

thread_Data adds;
adds = thread_Data{newSize, a11, a22, std::ref(r1)};  // here passing by std::ref

pthread_t adder;

pthread_create(&adder, NULL, add_Thread, &adds[i]);

pthread_join(adder, NULL);

/* and r1 value does not change here */

How to fix it?

NOTE: *add_Thread() works fine; I use array in my program. The code here is only to show idea.

16
  • 2
    std::ref doesn't magically make a non-reference a reference. thread_Data::result is not a reference. Also note that typedef struct is not required in C++. Just use struct thread_Data. I'm also not sure &adds[i] is doing what you think it's doing... adds is not an array. Commented Jun 19, 2020 at 19:37
  • Any reason you aren't using std::thread? It knows about std::reference_wrapper's and handles them correctly. Commented Jun 19, 2020 at 19:38
  • Yes it is not an array here. But in my program is. I just wanted to do a shortcut Commented Jun 19, 2020 at 19:40
  • @NathanOliver I'm beginner in threads Commented Jun 19, 2020 at 19:48
  • 2
    That's even more of a reason to use std::thread. It works with the type system, so no void pointers and casting has to be done. Commented Jun 19, 2020 at 19:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.