|
| 1 | +// Copyright 2015 The Emscripten Authors. All rights reserved. |
| 2 | +// Emscripten is available under two separate licenses, the MIT license and the |
| 3 | +// University of Illinois/NCSA Open Source License. Both these licenses can be |
| 4 | +// found in the LICENSE file. |
| 5 | + |
| 6 | +// This file tests pthread barrier usage. |
| 7 | + |
| 8 | +#include <pthread.h> |
| 9 | +#include <stdlib.h> |
| 10 | +#include <stdio.h> |
| 11 | +#include <assert.h> |
| 12 | + |
| 13 | +#define N 100 |
| 14 | +#define THREADS 8 |
| 15 | + |
| 16 | +int matrix[N][N] = {}; |
| 17 | +int intermediate[N] = {}; |
| 18 | + |
| 19 | +// Barrier variable |
| 20 | +pthread_barrier_t barr; |
| 21 | + |
| 22 | +// Sums a single row of a matrix. |
| 23 | +int sum_row(long r) { |
| 24 | + int sum = 0; |
| 25 | + for (int i = 0; i < N; ++i) { |
| 26 | + sum += matrix[r][i]; |
| 27 | + } |
| 28 | + return sum; |
| 29 | +} |
| 30 | + |
| 31 | +void* thread_main(void* arg) { |
| 32 | + // Each thread sums individual rows. |
| 33 | + long id = (long)arg; |
| 34 | + for (long i = id; i < N; i += THREADS) { |
| 35 | + intermediate[i] = sum_row(i); |
| 36 | + } |
| 37 | + |
| 38 | + // Synchronization point |
| 39 | + int rc = pthread_barrier_wait(&barr); |
| 40 | + if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { |
| 41 | + printf("Could not wait on barrier\n"); |
| 42 | + exit(-1); |
| 43 | + } |
| 44 | + |
| 45 | + // Then each thread sums the one intermediate vector. |
| 46 | + intptr_t totalSum = 0; |
| 47 | + for (int i = 0; i < N; ++i) { |
| 48 | + totalSum += intermediate[i]; |
| 49 | + } |
| 50 | + |
| 51 | + pthread_exit((void*)totalSum); |
| 52 | +} |
| 53 | + |
| 54 | +int main(int argc, char** argv) { |
| 55 | + pthread_t thr[THREADS]; |
| 56 | + |
| 57 | + // Create the matrix and compute the expected result. |
| 58 | + int expectedTotalSum = 0; |
| 59 | + for (int i = 0; i < N; ++i) { |
| 60 | + for (int j = 0; j < N; ++j) { |
| 61 | + matrix[i][j] = rand(); |
| 62 | + expectedTotalSum += matrix[i][j]; |
| 63 | + } |
| 64 | + } |
| 65 | + printf("The sum of the matrix is %d.\n", expectedTotalSum); |
| 66 | + |
| 67 | + // Barrier initialization |
| 68 | + int ret = pthread_barrier_init(&barr, NULL, THREADS); |
| 69 | + assert(ret == 0); |
| 70 | + |
| 71 | + for (intptr_t i = 0; i < THREADS; ++i) { |
| 72 | + pthread_create(&thr[i], NULL, &thread_main, (void*)i); |
| 73 | + } |
| 74 | + |
| 75 | + for (int i = 0; i < THREADS; ++i) { |
| 76 | + int totalSum = 0; |
| 77 | + pthread_join(thr[i], (void**)&totalSum); |
| 78 | + assert(totalSum == expectedTotalSum); |
| 79 | + } |
| 80 | + |
| 81 | + return 0; |
| 82 | +} |
0 commit comments