Calling a function more than once - c

So I'm programming a PIC using a CCS compliler. I'm using timer interrupt and this interrupt calls a function, called chronometer, that I wrote twice. This is how it goes
void timer2_isr()
{
j++;
l++;
z++;
if (j==1)
{
timero=1;
btndly=1;
j=0;
}
user1= chronometer(x, l);
user2= chronometer(pad.deger, z);
}
This function returns a struct and takes 2 integers as an argument. It works fine, when I just call the function once. However when, as in this case, I call the function twice, user2 is just equal to whatever user1 is and the code is not even working correctly. Any idea why?
chrono chronometer(int enable, int milicounter)
{
chrono time;
if(enable==1 && milicounter>=25) // Eğer kronometre aktif haldeyse
{
milicounter=0;
time.sec++;
if(time.sec==60)
{
time.sec=0;
time.min++;
}
if(time.min==60)
{
time.min=0;
time.hour++;
}
if(time.hour==24)
time.hour=0;
}
return time;
}

It seems you are starting to use the time struct without resetting it's members, resulting in unexpected results..
And even if it is somehow initialized.. it does not refer to the input parameters, so obviously the result will be the same..

Related

how to call a sub function only once within an periodically function call

I'm beginner with c and have a simple question:
I have a function myfunction() which is called periodically every 100 ms.
Within this function I have to call an other function but only once at the first call at beginn of myfunction(), but no periodically.
void myfunction() // function is called periodically every 100 ms
{
...
mySubfunction(); // this function have to be called only once in the first call of myFunction() and than skipped each time after that.
} ...
How to realize this in c?
Use static? Something along the lines of
void myfunction() // function is called periodically every 100 ms
{
static int once = 1;
if (once) {
mySubfunction();
once = 0;
}
}
The variable once in the example will be initalized only once and retain its value between invocations because of static keyword.
Be aware of implications in multithreaded environment, see this question.
you can have something like
static int flag = 1
void myfunction() // function is called periodically every 100 ms
{
if(flag)
{
mySubfunction();
flag = 0;
}
}
...
on first look task is very simply, can be next code:
void func()
{
static LONG first = TRUE;
if (_InterlockedExchange(&first, FALSE))
{
subfunc();
}
// some code
}
this give 100% guarantee that subfunc() will be called once and only once even if several thread in concurrent call your func()
but what be if // some code depended on result of subfunc ? in this case task become already not trivial. need some synchronization. and here already depended from os or compiler. in Windows, begin from Vista understand this problem and add function InitOnceExecuteOnce - read Using One-Time Initialization
if your subfunc() have no in and out parameters code can be very simply:
BOOL CALLBACK InitOnceCallback(PINIT_ONCE /*InitOnce*/, PVOID /*Parameter*/,PVOID* /*Context*/)
{
subfunc();
return TRUE;
}
void func()
{
static INIT_ONCE once = RTL_RUN_ONCE_INIT;
if (InitOnceExecuteOnce(&once, InitOnceCallback, 0, 0))
{
// somecode
}
// error init
}
also some modern compilers can correct handle static one time initialization. say latest versions of CL. with it code can be next:
void func()
{
static char tag = (subfunc(), 0);
// some code
}
here CL internally call special functions (implemented in CRT) _Init_thread_header, _Init_thread_footer - implementation can be look in crt source code - thread_safe_statics.cpp
This may be more advanced than you're looking for, but you could use function pointers and change which function gets called.
// Function declarations
void mySubfunction(void);
void myNormalfunction(void);
// Function pointer, which can be changed at run time.
static void (*myfunction)(void) = mySubfunction;
void mySubfunction(void)
{
// Do the sub-function stuff.
// Change the function pointer to the normal function.
myfunction = myNormalfunction();
// Do the normal function stuff (if necessary on the first call).
myNormalfunction();
}
void myNormalfunction(void)
{
// Etc.
}
int main(void)
{
int x;
for(x = 0; x < 3; x++)
{
// Call myfunction as you usually would.
myfunction();
}
return 0;
}

map function pointers to specific numbers at runtime

I have a problem that i can even start to work on because i don't get it how can be done.
So we have a code
int test_handler() {
printf("Test handler called\n");
return 1;
}
// Test your implementation here
int main()
{
register_irq_handler(30, &test_handler);
do_interrupt(29); // no handler registered at this position, should return zero
do_interrupt(30); // calls handler at position 30, expected output: Test handler called
return 0;
}
I need to make those functions register_irq_handler, do_interrupt(29).
But i have no clue how to start, i am looking for a little help to send me on the right direction.
How i store 30 to point to this function when we don't have a global variable to store that "connection" or i am missing something.
You can't do it without a global variable (why would having a global variable be a problem?).
You probably need something like this:
// array of 30 function pointers (all automatically initialized to NULL upon startup)
static int(*functionpointers[30])();
void register_irq_handler(int no, int(*fp)())
{
functionpointers[no] = fp;
}
int do_interrupt(int no)
{
if (functionpointers[no] != NULL)
{
// is registered (!= NULL) call it
return (*functionpointer[no])();
}
else
{
// not registered, just return 0
return 0;
}
}
Disclaimer
This is non tested non error checking code just to give you an idea.

Counting the number of function calls in an executable

I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:
//file1.c
int main(){
foo1();
return 0;
}
and other C files like:
//file2.c
void foo1(){
foo2();
...
foo2();
}
and
//file3.c
void foo2(){
foo3();
foo3();
foo3();
}
Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
BTW, I am compiling and running my project on Linux.
You can use 2 global variables (put extern at the places that access the variable outside the file you declare them) :
int foo1_active = 0;
int foo3_counter = 0;
then each time foo1 is called you increment it variable and before the return you decrement it:
void foo1() {
foo1_active++;
...
foo1_active--;
return
}
when foo3 is called you check if foo1 active and if it does you increment the counter:
void foo3() {
if foo1_active > 0 {
foo3_counter++;
}
...
}
You have an ubuntu flag, so I assume you are using gcc. I'd strongly consider adding -pg to your CFLAGS and trying out gprof.
Profiling works by changing how every function in your program is
compiled so that when it is called, it will stash away some
information about where it was called from. From this, the profiler
can figure out what function called it, and can count how many times
it was called. This change is made by the compiler when your program
is compiled with the `-pg' option, which causes every function to call
mcount (or _mcount, or __mcount, depending on the OS and compiler) as
one of its first operations.
You can count function calls using a static variable instead of global variable.
int inc(){
static int counter = 1;
counter++;
return counter;
}
int main(){
int i;
for (i = 0; i < 10; i++)
printf("%d\n", inc());
return 0;
}

Synchronizing the result of threads with incremented shared variable and condition

The title might not appear particularly clear, but the code explains itself:
int shared_variable;
int get_shared_variable() {
int result;
pthread_mutex_lock(&shared_variable_mutex);
result = shared_variable;
pthread_mutex_unlock(&shared_variable_mutex);
return result;
}
void* thread_routine(void *arg) {
while (get_shared_variable() < 5000) {
printf();
printf();
sleep(2);
int i = 0;
while (pthread_mutex_trylock(&foo_mutexes[i]) != 0) {
i++;
pthread_mutex_lock(&foo_count_mutex);
if (i == foo_count) {
pthread_mutex_unlock(&foo_count_mutex);
sleep(1); // wait one second and retry
i = 0;
}
pthread_mutex_unlock(&foo_count_mutex);
}
pthread_mutex_lock(&shared_variable_mutex);
shared_variable += 10;
pthread_mutex_unlock(&shared_variable_mutex);
}
return NULL;
}
I'm passing thread_routine to a pthread_create (pretty standard), but I'm having a problem with the synchronization of the result. Basically, the problem is that the first thread checks the while condition, it passes, and then another thread checks it, it passes too. However, when the first thread finishes and shared_variable reaches 5000, the second thread has not yet finished and it adds up another 10 and the end result becomes 5010 (or NUM_OF_THREADS - 1 * 10 if I run more than two) at the end, while the whole process should end at 5000.
Another issue is that in // do some work I output something on the screen, so the whole thing inside the loop should pretty much work as a transaction in database terms. I can't seem to figure out how to solve this problem, but I suppose there's something simple that I'm missing. Thanks in advance.
This answer may or may not be what you are after. Because as explained in the comments your description of the expected behaviour of the program is incomplete. Without the exact expected behaviour it is difficult to give a full answer. But since you ask, here is a possible structure of the program based on the code shown. The main principle it is illustrating is that the critical section for shared_variable needs to be both minimal and complete.
int shared_variable;
void* thread_routine(void *arg)
{
while (1) {
pthread_mutex_lock(&shared_variable_mutex);
if (shared_variable >= 5000) {
pthread_mutex_unlock(&shared_variable_mutex);
break;
}
shared_variable += 10;
pthread_mutex_unlock(&shared_variable_mutex);
/* Other code that doesn't use shared_variable goes here */
}
return NULL;
}

How to call more than one function in another function in C

I am trying to find out how it is possible to call different functions in different iterations in another function in C language. For example, suppose that the functions that I am doing the calling is A. In the first iteration I want to call function B in A but in all other iterations I want to call function C. Note that the iterations is not only on function A which is a part of a larger program so I can not put a for loop in this function.
You could use a locally-scoped static variable to keep track of if A has already been called:
void caller()
{
static int called_before = 0;
if (called_before)
{
B();
}
else
{
A();
called_before = 1;
}
}
In your function why not use a counter?:
static int count ;
if(count==0)
{
//call function B
}
else
{
//call function C
}
count++;
What you're asking requires some sort of state to be stored that is associated with and accessible to the function A.
The default state would indicate that the function has never been called, and then on the first call the function would check the state, see that it hasn't been called, and the change the state to indicate that it's been called, and then call function B.
All of the subsequent calls to A would check the state, see that it's been called, and call function C.
See the memento pattern for an explanation of maintaining state: http://en.wikipedia.org/wiki/Memento_pattern
Both #itsme86 and #brokenfoot have examples of doing this
Another possibility is using a global variable.
In a header called header_global.h put the following:
extern int GlobalVar=0;
and then in your function put
#include "header_global.h"
if (GlobalVar==0)
{
function_B();
GlobalVar++;
}
else
{
function_C();
}

Resources