Pointer to function and execute function n times
Hi
I have to fix the bug in code where function should be execute n times. Provided method is out of the times. Below code to fix
Code:
void execute (void (*action)(), int nTimes) {
for (int i = 0; i < nTimes; i += 1) {
action();
}
}
I have to idea to fix it in belowe way
Code:
static int i=0;
void pusty(void)
{i++;}
typedef void (*action)(void);
void execute (action pusty, int nTimes) {
for (; i < nTimes;) {
pusty();
}
}
but id doesn't work properly and I don't knowe where is mistake.
I think I know where is mistakie
I don't have to use static variable. I have to use thread. Code for sample test I put below.
Code:
#include <criterion/criterion.h>
#include <stdio.h>
#include <stdatomic.h>
#include <unistd.h>
void execute(void (*)(), int);
static atomic_int counter;
void thread() {
fputs(".", stdout);
sleep(1 /* second */);
counter += 1;
}
Test(the_multiply_function, should_pass_all_the_tests_provided) {
execute(&thread, 20);
if (counter != 20) {
cr_assert_fail("Action was executed %d times instead of %d times", counter, 20);
} else {
cr_assert(1);
}
}
The problem is how to wake thread while it is sleeping for 1 second.
The server codewars allow for 12 s time running code. I tried something like that. But it still doesn't work.
Code:
#include <omp.h>
#pragma omp parallel
void execute (void (*action)(), int nTimes) {
#pragma omp for schedule(dynamic, 1000)
for (int i = 0; i < nTimes; i += 1) {
action();
}
}
Can you give me some clues.