How to dispatch these functions in Objective C to not lock Main thread?

by Olia_Pavliuk   Last Updated January 13, 2018 10:05 AM

There's a large shared object (kind of OpenGL context) in my project. It is accessed from multiple threads. To ensure only one thread at the moments is using SHARED_OBJECT, mutex (kind of NSRecursiveLock) is used.

The problem is that sometimes MAIN_THREAD is waiting a lot while some BG_THREAD is doing something with SHARED_OBJECT.

I am not supposed to change architecture (to rewrite this mutex scheme).
The current problem lies in following: There is my_backround_func (takes a lot of time), which is called before main_thread_func1(takes few milliseconds) and main_thread_func2.

These functions are spread all over the project. To fix the problem, I created singleton class Dispatcher, which lets main_thread_func* to be registered, and lets my_backround_func to ask if all main_thread_funcs were already executed.

It uses Objective C mechanisms like NSStringFromSelector and "_cmd".

At the start of the program I register functions:

[[MyBackgroundFunctionDispatcher dispatcher] setCanCallBgFunc:NO forSelector:NSStringFromSelector(@selector(main_thread_func1:))];

[[MyBackgroundFunctionDispatcher dispatcher] setCanCallBgFunc:NO forSelector:NSStringFromSelector(@selector(main_thread_func2:))];

And at the end of main_thread_func1 and main_thread_func2 I call

[[MyBackgroundFunctionDispatcher dispatcher] setCanCallBgFunc:YES forSelector:NSStringFromSelector(_cmd)]; 

All this time background thread is waiting:

while ( ![[MyBackgroundFunctionDispatcher dispatcher] setCanCallBgFunc] )

So, I ensured that background function will be caller AFTER registered main thread functions. MyBackgroundFunctionDispatcher can be extended to hold registered functions not only for my_backround_func, but for my_backround_func1, my_backround_func2.

While the solution looks ugly and I suspect I miss some good pattern.

Could you give any advices please?

Related Questions

When to use embedded script language?

Updated September 10, 2017 02:05 AM

Where to learn iOS design best practice?

Updated March 25, 2017 20:05 PM