Call method using the main thread from the secondary thread

I called the method using a secondary thread. From inside the method, I need to call the method from the main thread.

here is the structure

void main_thread_method() { } void secondary_thread_method() { //do something here call main_thread_method() here using main thread } pthread thread1; pthread_create (&thread1, NULL, (void *) &secondary_thread_method, NULL); pthread_join(thread1); 
+4
source share
2 answers

If your main thread works with a message pump, you can send a message somehow to execute a function when your message is received.

Otherwise, there is a simple queue (corresponding lock, of course). Add enough data to the queue so that main_thread_method can be called. (args, etc.). Periodically try a simple queue for new messages in the main thread and process them.

+4
source

I realized that you want to call a method from the secondary thread that should run in the main thread. It's impossible. The called functions are executed in one thread. You use any method of multi-threaded exchange, for example semaphores, message pool, conditions, etc.

+1
source

Source: https://habr.com/ru/post/1379964/


All Articles