Fills an array in parallel and checks every item was written exactly once, whatever the slicing; that a small range runs on the caller alone; that an empty range does nothing; and that two parallel loops started at once from two threads, as workers of a pool do, both finish right while sharing one budget of cores.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (!ok) {
}
}
static void bump(
size_t begin,
size_t end,
void* user) {
int* items = (int*)user;
size_t i = 0;
for (i = begin; i < end; i++) items[i]++;
}
static void*
nested(
void* arg) {
return NULL;
}
static int all_ones(
const int* items,
size_t count) {
size_t i = 0;
for (i = 0; i < count; i++)
if (items[i] != 1) return 0;
return 1;
}
int* a = NULL;
int* b = NULL;
pthread_t other;
int slices = 0;
a = calloc(1000000, sizeof(int));
b = calloc(1000000, sizeof(int));
if (!a || !b) return 1;
expect_true(
"more than one slice on a machine with more than one core",
memset(a, 0, 1000000 * sizeof(int));
memset(a, 0, 1000000 * sizeof(int));
if (pthread_create(&other, NULL,
nested, b) != 0)
return 1;
pthread_join(other, NULL);
free(a);
free(b);
}
static void expect_true(const char *label, int cond)
static void * nested(void *arg)
a loop run from another thread, as a pool worker would
static void bump(size_t begin, size_t end, void *user)
add one to each item of the slice, so a slice done twice shows as a 2
static int all_ones(const int *items, size_t count)
every item is exactly one
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_ERR
error conditions
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL ).
#define LOG_NOTICE
normal but significant condition
int n_parallel_for(size_t begin, size_t end, size_t grain, N_PARALLEL_FN fn, void *user)
Run a loop over a range on several cores, and return when all of it is done.
long int get_nb_cpu_cores()
get number of core of current system
Common headers and low-level functions & define.