I always thought variables allocated on the stack vanish when the function returns / ends
However, using threads, I am seeing my variables persist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
// I only post portions of the very long code
// the input function called by below ev_init as argument
static int input_callback(int fd, short revents, void *data) {
struct input_event ev;
process_input(fd, ev);
...
}
// an input thread that will call back above function through ev_dispatch()
static void *input_thread(void *cookie)
{
for (;;) {
if (!ev_wait(-1))
ev_dispatch();
}
return NULL;
}
// init function creating above input thread and calling back input_callback function
ui_init() {
ev_init(input_callback, NULL)
pthread_t t;
pthread_create(&t, NULL, input_thread, NULL);
}
// ev_init calling the input function
int ev_init(ev_callback input_cb, void *data) {
...
}
// the ev_dispatch function called by input thread
void ev_dispatch(void)
{
unsigned n;
int ret;
for (n = 0; n < ev_count; n++) {
ev_callback cb = ev_fdinfo[n].cb;
if (cb && (ev_fds[n].revents & ev_fds[n].events))
cb(ev_fds[n].fd, ev_fds[n].revents, ev_fdinfo[n].data);
}
}
|
Well, the code is not mine, I am just working on it and customizing it
My question is:
My process_input(fd, ev) function can be simplified to my issue:
1 2 3 4 5 6 7 8 9 10 11 12
|
static int process_input(fd, ev) {
static int stack_var = 0;
if (condition1 == true)
stack_var = 1;
else if (condition2 == true)
stack_var = 0;
if (stack_var)
return good_catch;
else
return not_matched;
}
|
Now, starts my surprise:
process_input(fd, ev) function will be recursively called by input_callback() through input thread to process events. However, stack_var will not be initialized to zero on each call. The result from previous call will persist. That is, if I call it first time and condition1 is true, stack_var is set to 1.
Now, on second call if condition1 and condition2 are false, I will still have my stack_var == 1 and I get a good_catch
I added many logging code to track changes to stack_var which is only static inside function without any external occurance and I could confirm it clearly
Is this expected behaviour when calling threads that way?