The program has a cycle and a separate function in which the data is synchronized (a long operation, it takes more than 10 seconds). The loop uses a timer that starts this function after it expires. But while the function is executed, the cycle is worth it. Here is a sample program:

int sync(struct stack **data) { // обновляем массив data из файла } int main() { struct stack *data=NULL; struct itimerspec t={0}; struct timeval timeout={0,0}; int timerfd; uint64_t exp; t.it_value.tv_sec=50; t.it_interval.tv_sec=0; if ((timerfd=timerfd_create(CLOCK_REALTIME,TFD_NONBLOCK))==-1) {return EXIT_FAILURE;} if (timerfd_settime(timerfd,0,&t,0)==-1) {return EXIT_FAILURE;} while (TRUE) { if (read(timerfd,&exp,sizeof(uint64_t))>0) { sync(&data); } // проверка данных в массиве data и какие либо действия } } 

Is it possible to somehow run the sync function, say on the background, so that the loop runs on?

  • to run in a separate thread? - pavel
  • @pavel, can you give an example? - nerik
  • ru.cppreference.com/w/cpp/thread/thread think. you can fork of course. - pavel
  • @pavel, and will the data array in the parent be updated? - nerik
  • If you write correctly, then yes, but you need to be careful to read only after the recording has ended. - pavel

2 answers 2

I give an example using the Glib library, but working with threads is similar to other libraries.

create a structure in which are processed double

 typedef struct _data_s data_s; struct _data_s { int first; }; 

create a semaphore controlling access to data

 GMutex mutex; 

create a separate thread function that will process data

 static gpointer thread_fun(gpointer d) { data_s * data = (data_s*)d; for(;;){ int local_first; /*чтение данных*/ g_mutex_lock(&mutex); local_first = data->first; g_mutex_unlock(&mutex); /*обработка данных*/ .... /*запись данных*/ g_mutex_lock(&mutex); data->first = local_first; g_mutex_unlock(&mutex); /*если требуется накопление данных*/ g_usleep(TIMEOUT); } return NULL; 

}

and in the main function, start the stream, accumulate data and transfer it to the processing flow

 int main(int argc,char * argv[]) { GThread * thread; data_s data; data.first = 5; g_mutex_init(&mutex); thread = g_thread_new("data",thread_fun,&data); for(;;){ g_mutex_lock(&mutex); data->first = read(); g_mutex_unlock(&mutex); } return 0; } 
  • Thanks for the example, I will try. If everything works out, I will accept the answer. - nerik
  • And what include is required for streams? - nerik
  • if you use the glib library. #include <glib.h> - Yaroslav
  • I understand correctly that glib is not a regular library? - nerik
  • Not that it is completely regular, but if GTK-based programs are installed, then GLib is also there. - Yaroslav

For such purposes, it is possible to use separate streams.