简体   繁体   中英

Calling method using main thread from secondary thread

I have called a method using a secondary thread. From inside the method i need to call a method from 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);

If your main thread is running a message pump you can post a message somehow to execute a function when your message is received.

Otherwise have a simple queue ( appropriate locking of course ). Add enough data into the queue so that main_thread_method can be called. (args etc). Periodically poll the simple queue for new messages in the main thread and process them.

I understood you want to invoke, from secondary thread, a method that must run in main thread. This is not possible. Invoked functions runs in the same thread. You mus use any kind of multi-threading communication method like semaphores, messages pooling, conditions, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM