File: multiply.c

package info (click to toggle)
smlsharp 4.2.0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 125,348 kB
  • sloc: ansic: 16,737; sh: 4,347; makefile: 2,228; java: 742; haskell: 493; ruby: 305; cpp: 284; pascal: 256; ml: 255; lisp: 141; asm: 97; sql: 74
file content (64 lines) | stat: -rw-r--r-- 1,216 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * naive parallel matrix multiplication
 */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define DIM (2*3*5*7*8)   /* dividable by 1 - 8 */
static double matrix1[DIM][DIM];
static double matrix2[DIM][DIM];
static double result[DIM][DIM];
static unsigned int nthreads;

static void *
calc(void *arg)
{
	unsigned int start = (unsigned int)arg;
	unsigned int i, j, k;

	for (i = start; i < start + DIM / nthreads; i++) {
		for (j = 0; j < DIM; j++) {
			double d = 0.0;
			for (k = 0; k < DIM; k++)
				d += matrix1[i][k] * matrix2[k][j];
			result[i][j] = d;
		}
	}
	return NULL;
}

int
main(int argc, char **argv)
{
	unsigned int i, j, start;
	int err;
        pthread_t *th;

	nthreads = 1;
	if (argc == 2)
		nthreads = atoi(argv[1]);

        th = malloc(sizeof(pthread_t) * nthreads);
	if (th == NULL) abort();

	for (i = 0; i < DIM; i++)
		for (j = 0; j < DIM; j++)
			matrix1[i][j] = matrix2[i][j] = 1.2345678;

	for (i = 1; i < nthreads; i++) {
		start = i * DIM / nthreads;
		err = pthread_create(&th[i], NULL, calc, (void*)start);
		if (err != 0) abort();
	}

	calc((void*)0);

	for (i = 1; i < nthreads; i++) {
		err = pthread_join(th[i], NULL);
		if (err != 0) abort();
	}

	return 0;
}