communication between threads must be as short as possible.
thread terminates when
Any divide and conquer problems are embarrassingly parallel.
It only requires termination syncronization at the end.
example program - adds all numbers in matrix
#include <uCobegin.h>
int main(){
const int rows = 10, col = 10;
int matrix[rows][cols], subtotals[rows], total = 0;
// read matrix
COFOR(r, 0, rows, // like for(int r=0;r<rows;r++){
subtotals[r] = 0;
for(int c=0; c<cols; c++){
subtotals[r] += matrix[r][c];
}
);// waits for threads to finish
// do syncronous addup to subtotals
for(int r=0; r<rows; r++){
total += subtotals[r];
}
cout << total << endl;
}
This is implicit because COBEGIN is implicit and COFOR is built on COBEGIN
Actor example of same program
_Actor Adder{
int * row, cols, & subtotal;
Allocation receive(Message &){
subtotal = 0;
for(int c=0;c<cols;c++) subtotal += rows[c];
return Delete;
}
public:
Adder(int row[], int cols, int &subtotal):
row(row), cols(cols), subtotal(subtotal){}
};
int main(){
...
uActorStart(); // start actor system
for(int r=0; r<rows,; r++){
*new Adder(matrix[r],cols,subtotals[r]) | uActor::startMsg;
}
uActorStop();
...
}
Task example
_Task Adder {
int * row, cols, &subtotal; // communication
void main() {
subtotal = 0;
for ( int c = 0; c < cols; c += 1 ) {
subtotal += row[c];
}
}
public:
Adder( int row[ ], int cols, int &subtotal ) :
row( row ), cols( cols ), subtotal( subtotal ) {}
};
int main() {
const int rows = 10, cols = 10;
int matrix[rows][cols], subtotals[rows], total = 0, r;
// read matrix
Adder * adders[rows];
for ( r = 0; r < rows; r += 1 ) { // start threads to sum rows
adders[r] = new Adder( matrix[r], cols, subtotals[r] );
}
for ( r = 0; r < rows; r += 1 ) { // wait for threads to finish
delete adders[r];
total += subtotals[r]; // total subtotals
}
cout << total << endl;
}
tasks has stack so it can raise exceptions like coroutines.
local exceptions just work as before.
non-local exceptions are possible
whats different with coroutine is that when you throw non-local exception, the routine that is receiving exception has its own thread, so its already running.