0

I have an app that can spawn any given number of threads. So I'd like this code to become multithreaded

void *some_thread_fuction(void *param)
{
    struct some_struct *obj=(struct some_struct *)param;
    int m=obj->m;
    int n=...
    double t[m+2][n+2]={0};
    
    for (i=0; i <= m+1; i++) {
        for (j=0; j <= n+1; j++) {
            t[i][j] = 30.0;
        }
    }


    for (i=1; i <= m; i++) {
        t[i][0] = 40.0;
        t[i][n+1] = 90.0;
    }
    for (j=1; j <= n; j++) {
        t[0][j] = 30.0;
        t[m+1][j] = 50.0;
    }
    memcpy(global_t,t,...);
}

I am having simple reasoning issue as to why I like to make this a multi-threaded program. but it make sense because if I have 5 threads (assumed I am taking how many number of threads to spawn at program start in program parameter) and n=20 m=20 which is also fed at program start as parameters then I can try working on 0-4 in one thread, 5-8 in second thread and so on until 16-20 in last iteration of first loop(just an example, because m=etc n=etc and number of threads can be anything values fed by user).

But more importantly I am having tough time as to how to even dissect the three for loops to distribute the processing over amount of work to multiple threads to completion of all the loops in this code. This is simple code, so it's just a real world example that I am having difficulty understanding how to do it in code for a threaded program for this scenario.

3
  • So you want to spawn threads and give start and end offset in the matrix as thread arguments? Commented Dec 8, 2021 at 10:41
  • @kiner_shah sounds like u understood. Thanks for comment Commented Dec 8, 2021 at 10:47
  • @kiner_shah its simple Commented Dec 8, 2021 at 10:53

1 Answer 1

1

Move this piece of code into a function:

    for (i=0; i <= m+1; i++) {
        for (j=0; j <= n+1; j++) {
            t[i][j] = 30.0;
        }
    }

as follows:

void initialize(double t[], int start_i, int end_i, int n) {
    for (i=start_i; i <= end_i; i++) {
        for (j=0; j <= n+1; j++) {
            t[i][j] = 30.0;
        }
    }
}

You can then split the interval [0 m+1] into as 5 intervals and call the initialize function from each thread for each interval.

That said, there must be more efficient ways to achieve the same thing using some copy instructions.

Sign up to request clarification or add additional context in comments.

2 Comments

Please do tell so do I need to implement function for 40 90 50 myself. Did u left it as an exercise for me. Or I can use same function to edit values which I think so.
Well, I am certain you got the idea.

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.