diff options
| author | Sebastiano Tronto <sebastiano@tronto.net> | 2025-06-05 10:13:28 +0200 |
|---|---|---|
| committer | Sebastiano Tronto <sebastiano@tronto.net> | 2025-06-05 10:13:28 +0200 |
| commit | 73efecca42dbc44200e797e02f8c1e24fcff26ef (patch) | |
| tree | 46969fed9d5c09a4164257dace56a71cad9092ab /05_callback/primes.c | |
| parent | 2a8e7aeeef99161b6f0378ac14e297c23ca6227b (diff) | |
| download | emscripten-tutorial-73efecca42dbc44200e797e02f8c1e24fcff26ef.tar.gz emscripten-tutorial-73efecca42dbc44200e797e02f8c1e24fcff26ef.zip | |
Added two more examples
Diffstat (limited to '')
| -rw-r--r-- | 05_callback/primes.c | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/05_callback/primes.c b/05_callback/primes.c new file mode 100644 index 0000000..f581161 --- /dev/null +++ b/05_callback/primes.c | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | #include <stdbool.h> | ||
| 2 | #include <pthread.h> | ||
| 3 | |||
| 4 | #define NTHREADS 16 | ||
| 5 | |||
| 6 | bool isprime(int); | ||
| 7 | void *pthread_routine(void *); | ||
| 8 | |||
| 9 | struct interval { int low; int high; int count; }; | ||
| 10 | |||
| 11 | int primes_in_range(int low, int high, void (*log)(const char *)) { | ||
| 12 | pthread_t threads[NTHREADS]; | ||
| 13 | struct interval args[NTHREADS]; | ||
| 14 | |||
| 15 | if (low < 0 || high < low) | ||
| 16 | return 0; | ||
| 17 | |||
| 18 | int interval_size = (high-low)/NTHREADS + 1; | ||
| 19 | for (int i = 0; i < NTHREADS; i++) { | ||
| 20 | args[i].low = low + i*interval_size; | ||
| 21 | args[i].high = args[i].low + interval_size; | ||
| 22 | pthread_create(&threads[i], NULL, pthread_routine, &args[i]); | ||
| 23 | } | ||
| 24 | |||
| 25 | log("All threads have started, computing..."); | ||
| 26 | |||
| 27 | int result = 0; | ||
| 28 | for (int i = 0; i < NTHREADS; i++) { | ||
| 29 | pthread_join(threads[i], NULL); | ||
| 30 | result += args[i].count; | ||
| 31 | } | ||
| 32 | |||
| 33 | return result; | ||
| 34 | } | ||
| 35 | |||
| 36 | bool isprime(int n) { | ||
| 37 | if (n < 2) | ||
| 38 | return false; | ||
| 39 | |||
| 40 | for (int i = 2; i*i <= n; i++) | ||
| 41 | if (n % i == 0) | ||
| 42 | return false; | ||
| 43 | return true; | ||
| 44 | } | ||
| 45 | |||
| 46 | void *pthread_routine(void *arg) { | ||
| 47 | struct interval *interval = arg; | ||
| 48 | |||
| 49 | interval->count = 0; | ||
| 50 | for (int i = interval->low; i < interval->high; i++) | ||
| 51 | if (isprime(i)) | ||
| 52 | interval->count++; | ||
| 53 | |||
| 54 | return NULL; | ||
| 55 | } | ||
