Path: blob/main/test/core/pthread/exceptions.cpp
4154 views
// Copyright 2019 The Emscripten Authors. All rights reserved.1// Emscripten is available under two separate licenses, the MIT license and the2// University of Illinois/NCSA Open Source License. Both these licenses can be3// found in the LICENSE file.45#include <stdio.h>6#include <stdlib.h>7#include <pthread.h>8#include <assert.h>9#include <emscripten.h>1011#include <atomic>1213#define NUM_THREADS 214#define TOTAL 100015#define THREAD_ADDS 75016#define MAIN_ADDS 51718static std::atomic<int> sum;19static std::atomic<int> total;2021void *ThreadMain(void *arg) {22for (int i = 0; i < TOTAL; i++) {23try {24// Throw two different types, to make sure we check throwing and landing25// pad behavior.26if (i & 3) {27throw 3.14159f;28}29throw i;30} catch (int x) {31total += x;32} catch (float f) {33// wait for a change, so we see interleaved processing.34int last = ++sum;35while (sum.load() == last) {}36}37}38pthread_exit((void*)TOTAL);39}4041pthread_t thread[NUM_THREADS];4243void CreateThread(int i)44{45int rc = pthread_create(&thread[i], nullptr, ThreadMain, (void*)(intptr_t)i);46assert(rc == 0);47}4849void loop() {50static int main_adds = 0;51int worker_adds = sum++ - main_adds++;52printf("main iter %d : %d\n", main_adds, worker_adds);53if (worker_adds == NUM_THREADS * THREAD_ADDS &&54main_adds >= MAIN_ADDS) {55printf("done: %d.\n", total.load());56emscripten_cancel_main_loop();57exit(0);58}59}6061int main() {62// Create initial threads.63for (int i = 0; i < NUM_THREADS; ++i) {64printf("make\n");65CreateThread(i);66}6768emscripten_set_main_loop(loop, 0, 0);69return 0;70}717273