2

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] )
    sleep_ms(10);

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?

  • Why NSStringFromSelector? A selector itself does all you need. – gnasher729 Jan 13 '18 at 18:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.