DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Parallelize Friendly Number Searches in C with OpenMP Without Schedule Traps

Adding #pragma omp parallel for to a CPU-bound C loop looks simple until a bad schedule clause leaves threads idle or hangs on small inputs. Number-theoretic searches expose those bugs fast because divisor checks grow heavier with integer size, while floating-point shortcuts raise precision questions.

paladini/UFSC-concurrent-programming is an MIT-licensed repository of C concurrency labs covering POSIX threads, semaphores, and OpenMP. Its third project compares a sequential friendly-number search (mutuamenteAmigosSeq.c) with an OpenMP version (mutuamenteAmigosParalelo.c). Two distinct integers a and b are friendly (OEIS A014567) when they share the abundancy index sigma(a) / a == sigma(b) / b, where sigma(n) sums positive divisors of n. Both 6 and 28 reduce to 2/1.

In this tutorial, you will inspect the master OpenMP code, reproduce two scheduling traps with GCC, write a C11 and OpenMP verification harness with reduced fractions, and verify thread invariance.

TL;DR

  • Zero Git tags or GitHub releases exist; all files live on master at 4fcd7e6 under the MIT License.
  • In mutuamenteAmigosParalelo.c, schedule(dynamic, intervalo/threads) truncates the chunk size to 0 when maximo - minimo < threads (./par 1 3 4), hanging libgomp, and blocks dynamic rebalancing on larger ranges.
  • Nesting #pragma omp parallel inside the outer loop with schedule(guided, intervalo) sets the minimum chunk size to the loop bound, starving threads - 1 workers every pass.
  • Computing sigma(n) in O(sqrt(n)), storing reduced (num, den) pairs via gcd, and parallelizing the outer loop with reduction(+:pairs) yields 92 pairs in [1, 5000] across 1, 2, and 4 threads.

Prerequisites

  • A C11 compiler with OpenMP support (gcc --version; verified on GCC 13.2.0 MinGW-W64 x86_64-ucrt-posix-seh with libgomp).
  • Git to clone paladini/UFSC-concurrent-programming at commit 4fcd7e6.
  • Familiarity with C structs, <stdint.h> integers, and loop directives in the OpenMP Specifications.

Minimal Working Path

Clone the repository, confirm the commit hash, and compile both original files with warnings:

git clone https://github.com/paladini/UFSC-concurrent-programming.git
cd UFSC-concurrent-programming
git rev-parse --short HEAD
gcc -O2 -Wall -Wextra trabalhos/trabalho_3/mutuamenteAmigosSeq.c -o seq
gcc -O2 -Wall -Wextra -fopenmp trabalhos/trabalho_3/mutuamenteAmigosParalelo.c -o par
Enter fullscreen mode Exit fullscreen mode

GCC warns about unused parameter 'argc' in both files because main calls atoi(argv[1]) through atoi(argv[3]) unchecked. Inspecting mutuamenteAmigosParalelo.c shows both OpenMP phases:

omp_set_num_threads(threads);
#pragma omp parallel
{
    #pragma omp for schedule(dynamic, intervalo/threads)
    for (i = minimo; i <= maximo; i++) {
        fracoes[i - minimo] = (double)calculaSomaDosDivisores(i) / i;
    }
}
for(i = 0; i <= intervalo; i++){
    #pragma omp parallel
    {
        #pragma omp for schedule(guided, intervalo)
        for (j = i+1; j <= intervalo; j++) {
            if(fracoes[i] == fracoes[j]) {
                //printf("Os numeros %d e %d sao mutuamente amigos.\n", (minimo + i), (minimo + j));
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Because printf is commented out, ./par 1 300 4 exits 0 silently. Do not run ./par 1 3 4 without a timeout: intervalo = 2 and threads = 4, so intervalo / threads equals 0, violating OpenMP's positive-chunk rule and hanging par.

Save verify_friendly_openmp.c in the parent directory. It validates O(sqrt(n)) divisor sums against the legacy routine, measures thread starvation under schedule(guided, intervalo), uses reduced uint64_t fractions, and checks thread invariance:

#include <inttypes.h>
#include <omp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct { uint64_t num, den; } Ratio;

static uint64_t gcd_u64(uint64_t a, uint64_t b) {
    while (b) { uint64_t t = a % b; a = b; b = t; }
    return a;
}

static uint64_t sum_div(uint64_t n) {
    uint64_t s = 0;
    for (uint64_t d = 1; d * d <= n; d++) {
        if (n % d == 0) s += d + (n / d != d ? n / d : 0);
    }
    return s;
}

static int legacy_sum(int i) {
    int s = i;
    for (int j = i / 2; j > 0; j--) if (i % j == 0) s += j;
    return s;
}

static Ratio abundancy(uint64_t n) {
    uint64_t s = sum_div(n), g = gcd_u64(s, n);
    return (Ratio){ s / g, n / g };
}

static uint64_t count_pairs(uint64_t lo, uint64_t hi, int threads) {
    if (!lo || hi < lo || threads <= 0) return 0;
    uint64_t n = hi - lo + 1, pairs = 0;
    Ratio *r = malloc(n * sizeof(*r));
    if (!r) exit(1);

    omp_set_num_threads(threads);
    #pragma omp parallel for schedule(dynamic, 64)
    for (int64_t k = 0; k < (int64_t)n; k++) r[k] = abundancy(lo + (uint64_t)k);

    #pragma omp parallel for schedule(dynamic, 16) reduction(+:pairs)
    for (int64_t i = 0; i < (int64_t)n; i++) {
        for (uint64_t j = (uint64_t)i + 1; j < n; j++) {
            if (r[i].num == r[j].num && r[i].den == r[j].den) pairs++;
        }
    }
    free(r);
    return pairs;
}

int main(void) {
    for (int n = 1; n <= 2000; n++) {
        if (sum_div((uint64_t)n) != (uint64_t)legacy_sum(n)) return 1;
    }

    int span = 299, hits[4] = {0}, active = 0, top = 0;
    omp_set_num_threads(4);
    #pragma omp parallel
    {
        int tid = omp_get_thread_num();
        #pragma omp for schedule(guided, span)
        for (int j = 1; j <= span; j++) hits[tid]++;
    }
    for (int t = 0; t < 4; t++) {
        active += hits[t] > 0;
        if (hits[t] > top) top = hits[t];
    }
    printf("guided(%d): active=%d/4, max_iters=%d\n", span, active, top);

    printf("Friendly pairs in [1, 300]:\n");
    for (uint64_t a = 1; a <= 300; a++) {
        Ratio ra = abundancy(a);
        for (uint64_t b = a + 1; b <= 300; b++) {
            Ratio rb = abundancy(b);
            if (ra.num == rb.num && ra.den == rb.den) {
                printf("  (%" PRIu64 ", %" PRIu64 ") -> %" PRIu64 "/%" PRIu64 "\n",
                       a, b, ra.num, ra.den);
            }
        }
    }

    printf("Range [1, 3] on 4T: %" PRIu64 " pairs\n", count_pairs(1, 3, 4));
    uint64_t p1 = count_pairs(1, 5000, 1), p2 = count_pairs(1, 5000, 2), p4 = count_pairs(1, 5000, 4);
    printf("Range [1, 5000]: 1T=%" PRIu64 ", 2T=%" PRIu64 ", 4T=%" PRIu64 "\n", p1, p2, p4);
    return (p1 == 92 && p1 == p2 && p1 == p4) ? 0 : 1;
}
Enter fullscreen mode Exit fullscreen mode

Expected Result and Reproducible Verification

Compile verify_friendly_openmp.c with strict warnings treated as errors and run it:

gcc -std=c11 -O2 -Wall -Wextra -Werror -fopenmp verify_friendly_openmp.c -o verify_friendly_openmp
./verify_friendly_openmp
Enter fullscreen mode Exit fullscreen mode

The binary exits with status 0 and prints:

guided(299): active=1/4, max_iters=299
Friendly pairs in [1, 300]:
  (6, 28) -> 2/1
  (12, 234) -> 7/3
  (30, 140) -> 12/5
  (40, 224) -> 9/4
  (80, 200) -> 93/40
  (84, 270) -> 8/3
Range [1, 3] on 4T: 0 pairs
Range [1, 5000]: 1T=92, 2T=92, 4T=92
Enter fullscreen mode Exit fullscreen mode

Each line checks a concrete invariant: (6, 28) reduces to 2/1, (30, 140) reduces 72/30 and 336/140 to 12/5, [1, 3] finishes on 4 threads, and [1, 5000] returns 92 pairs across thread counts.

Why It Works

  1. Positive constant chunks replace intervalo / threads. OpenMP requires chunk_size >= 1 on schedule(dynamic, chunk_size). Fixed chunks like 64 prevent truncation to 0 when n < threads and keep workers pulling batches as uneven divisor sums finish.
  2. Outer-loop parallelism with reduction(+:pairs). Entering #pragma omp parallel inside an outer loop pays barrier overhead intervalo + 1 times. In schedule(guided, chunk_size), chunk_size sets the minimum block size, so guided, span hands all 299 iterations to one thread (active=1/4). Moving #pragma omp parallel for schedule(dynamic, 16) reduction(+:pairs) to the outer loop forms one team, balances shrinking inner loops, and sums counts lock-free.
  3. Exact reduced rationals and O(sqrt(n)) divisor sums. Pairing d with n / d up to d * d <= n matches calculaSomaDosDivisores while cutting per-integer work to O(sqrt(n)). Reducing (sigma(n), n) by gcd_u64 stores canonical fractions: distinct reduced ratios a/b and c/d differ by at least 1 / (b * d), whereas IEEE-754 double has 53 significand bits and can collide once b * d > 2^53 (n above 9.49e7).

Failure Modes, Limitations, and Security Boundaries

  • No tagged releases. paladini/UFSC-concurrent-programming is a 2014 coursework repository without version tags; pin 4fcd7e6.
  • Unvalidated CLI inputs in original files. Fewer than three arguments in mutuamenteAmigosParalelo.c dereferences NULL in atoi, minimo <= 0 divides by zero (NaN), and maximo < minimo wraps allocation sizes. Parse inputs with strtoull, reject 0 and inverted bounds, and cap hi - lo before malloc.
  • Quadratic pair matching. Scanning (i, j) pairs takes O(N^2) comparisons (16 bytes per Ratio). Larger ranges should sort Ratio entries by (num, den) and count equal runs in O(N log N).
  • Separate bugs in sibling folders. Other exercises have independent defects (trabalhos/trabalho_1/trabalho1.c calls pthread_mutex_destroy and pthread_exit(NULL) before pthread_join); audit each folder separately.

FAQ

Why did ./par 1 3 4 hang instead of crashing?

In C integer division, 2 / 4 equals 0. Passing chunk_size = 0 to schedule(dynamic, chunk_size) violates OpenMP's positive-chunk rule, causing libgomp to spin without advancing bounds.

Does double fail on [1, 5000]?

No. Below 5000, distinct ratios differ by at least 4e-8, well inside double precision. Reduced uint64_t pairs remove rounding concerns as bounds grow.

Why use dynamic instead of static on the outer loop?

Iteration i checks n - 1 - i pairs, so early indices do far more work than late ones. Dynamic chunks rebalance threads once short blocks finish.

Takeaway

Parallelizing C loops safely with OpenMP means checking what schedule arguments assign per thread, guarding small ranges where integer division hits zero, and verifying multi-thread output against a single-thread baseline.

Disclosure: Researched and drafted with AI assistance. Every file on master (4fcd7e6), GCC warning, libgomp hang condition, thread count, and OpenMP verification result was compiled and verified locally on GCC 13.2.0.

When you add OpenMP pragmas to a C or C++ loop, how do you verify that your schedule clause distributes iterations across threads instead of starving them?

Top comments (0)