//                               -*- Mode: C -*- 
// 
// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
// 
// matrixSum.c -- 
// 
// Author           : Peter A. Buhr
// Created On       : Mon Oct  9 08:29:28 2017
// Last Modified By : Peter A. Buhr
// Last Modified On : Tue Dec  5 22:56:46 2017
// Update Count     : 4
// 

#include <fstream>
#include <kernel>
#include <thread>

thread Adder {
    int * row, cols, * subtotal;						// communication
};

void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
    adder.row = row;
    adder.cols = cols;
    adder.subtotal = &subtotal;
}

void main( Adder & adder ) with( adder ) {
    *subtotal = 0;
    for ( int c = 0; c < cols; c += 1 ) {
		*subtotal += row[c];
    } // for
}

int main() {
    const int rows = 10, cols = 1000;
    int matrix[rows][cols], subtotals[rows], total = 0;
    processor p;										// extra kernel thread

    for ( int r = 0; r < rows; r += 1 ) {
		for ( int c = 0; c < cols; c += 1 ) {
			matrix[r][c] = 1;
		} // for
    } // for
    Adder * adders[rows];
    for ( int r = 0; r < rows; r += 1 ) {				// start threads to sum rows
		adders[r] = &(*malloc()){ matrix[r], cols, subtotals[r] };
//		adders[r] = new( matrix[r], cols, &subtotals[r] );
    } // for
    for ( int r = 0; r < rows; r += 1 ) {				// wait for threads to finish
		delete( adders[r] );
		total += subtotals[r];							// total subtotals
    } // for
    sout | total | endl;
}

// Local Variables: //
// tab-width: 4 //
// compile-command: "cfa matrixSum.c" //
// End: //
