0

Ich versuche derzeit, ein C++ - Programm mit Pthreads.h für Multi-Thread-Matrix-Multiplikation zu schreiben.pthreads Multi-Thread-Matrix-Multiplikation

Ich versuche, die Fäden zu schaffen, wie

int numthreads = (matrix[0].size() * rsize2);//Calculates # of threads needed 
pthread_t *threads; 
threads = (pthread_t*)malloc(numthreads * sizeof(pthread_t));//Allocates memory for threads 
int rc; 
for (int mult = 0; mult < numthreads; mult++)//rsize2 
{ 
    struct mult_args args; 
    args.row = mult; 
    args.col = mult; 
    cout << "Creating thread # " << mult; 
    cout << endl; 
    rc = pthread_create(&threads[mult], 0, multiply(&args), 0); 
} 

Dieser erstellt dann Fäden folgt, dass meine Multiplikationsfunktion ausführen, die wie folgt codiert

void *multiply(int x, int y) 
{ 
    int oldprod = 0, prod = 0, sum = 0; 
    cout << "multiply"; 

    for(int i = 0; i < rsize2; i++)//For each row in #ofrows in matrix 2 
    { 
     prod = matrix[x][i] * matrix2[i][y];//calculates the product 
     sum = oldprod + prod; //Running sum starting at 0 + first product 
     oldprod = prod; //Updates old product 
    } 

Mein Fehler in meiner Multiplikationsfunktion liegt. Ich versuche, einen kompatiblen Weg zu finden, um eine x- und y-Koordinate für jeden Thread zu übergeben, so dass er genau weiß, welche Summe zu berechnen ist, aber ich bin mir nicht sicher, wie dies für die Funktion pthreads_create() akzeptabel ist .

Update: Ich weiß, dass ich eine Struktur zu verwenden, haben diese

struct mult_args { 
    int row; 
    int col; 
}; 

zu erreichen, aber ich kann nicht die Multiplikationsfunktion erhalten die Struktur

+0

Warum nicht 'std :: thread' an erster Stelle? – user0042

+0

pthreads ist eine Voraussetzung für das Projekt – Zac

+0

_pthreads ist eine Voraussetzung für das Projekt_ YAIT (noch ein inkompetenter Lehrer) –

Antwort

0

Sie Ihre multiply ändern wird akzeptieren müssen, Funktion, so dass es einen einzigen void* Parameter benötigt. Dazu müssen Sie eine Struktur erstellen, um x und y zu speichern und einen Zeiger darauf in pthread_create übergeben.

struct multiply_params 
{ 
    int x; 
    int y; 

    multiply_params(int x_arg, int y_arg) noexcept : 
     x(x_arg), y(y_arg) 
    {} 
}; 

// ... 

for (int mult = 0; mult < numthreads; mult++) 
{ 
    cout << "Creating thread # " << mult; 
    cout << endl; 

    multiply_params* params = new multiply_params(1, 0); 
    rc = pthread_create(&threads[mult], 0, multiply, (void*) params); 
} 

Dann in Ihrer Multiplikationsfunktion, umschreiben es so, einen einzigen void* Parameter genommen wird, die der Zeiger von multiply_params sein wird, die wir in pthread_create geben. Sie müssen dieses Argument aus void* umwandeln, damit wir auf seine Felder zugreifen können.

void* multiply(void* arg) 
{ 
    multiply_params* params = (multiply_params*) arg; 

    int x = params->x; 
    int y = params->y; 

    delete params; // avoid memory leak   
    // ... 
}