Search code examples
c++pthreadsposix

posix pthread work on array elements in separate threads


I am trying to learn posix and want to start from somethig simple. I want to work on array elements on different threads. My code is:

#include <iostream>
#include <pthread.h>
using namespace std;

static void* doWork(int* a, size_t s) {
    for(int i = 0; i < s; i++) {
        a[i] = a[i] * 2;
    }
    //return void;
}

void printIntArr(int* a, size_t s) {
    for(int i = 0; i < s; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

int main() {

    int a[24];
    for(int i = 0; i < 24; i++) {
        a[i] = i;
    }

    printIntArr(&a[0], 24); //before

    //I want to make 2 threads, and pass first half and second half of the array to process
    pthread_t tA, tB;
    int resultA =  pthread_create(&tA, NULL, &doWork(&a[0],12), NULL);
    int resultB =  pthread_create(&tB, NULL, &doWork(&a[11],12), NULL);

    printIntArr(&a[0], 24); //after

    return 0;
}

I just want to perform doWork function on first and second half of the array on different threads. And yes my code does not compile.


Solution

  • #include <iostream>
    #include <pthread.h>
    using namespace std;
    
    typedef struct {
        int* a;
        size_t s;
    } Params;
    
    static void* doWork(void * data) {
        Params * p = (Params *) data;
        for(int i = 0; i < p -> s; i++) {
            p ->a[i] = p ->a[i] * 2;
        }
        //return void;
        return data;
    }
    
    void printIntArr(int* a, size_t s) {
        for(int i = 0; i < s; i++) {
            cout << a[i] << " ";
        }
        cout << endl;
    }
    
    int main() {
    
        int a[24];
        for(int i = 0; i < 24; i++) {
            a[i] = i;
        }
    
        printIntArr(&a[0], 24); //before
    
        Params p1;
        p1.a = &(a[0]);
        p1.s = 12;
    
        Params p2;
        p2.a = &(a[11]);
        p2.s = 12;
    
    
        //I want to make 2 threads, and pass first half and second half of the array to process
        pthread_t tA, tB;
        int resultA =  pthread_create(&tA, NULL, doWork, (void *)&p1);
        int resultB =  pthread_create(&tB, NULL, doWork, (void *)&p2);
    
        pthread_join(tA, NULL);
        pthread_join(tA, NULL);
    
        printIntArr(&a[0], 24); //after
    
        return 0;
    }
    

    If you are coding in c++, you may use this one: http://cpp.sh/4du5