Is there a way to get into Cocoa multithreaded without creating fake NSThread?

The Apple Threading Guide says:

For multi-threaded applications, Cocoa frameworks use locks and other forms of internal synchronization to ensure proper operation. However, to prevent these locks from degrading performance in the single-threaded case, Cocoa does not create them until the application creates its first new thread using the NSThread class. If you create threads using only the POSIX thread routines, Cocoa does not receive notifications, he should know that your application is now multithreaded. When this happens, Cocoa infrastructure operations can destabilize or collapse your application.

So that Cocoa knows that you intend to use multiple threads, all you have to do is create one thread using the NSThread class and immediately open that thread. The entry point to the stream is not needed. Just to create a thread using NSThread is enough to ensure that the locks needed for Cocoa frameworks are set in place.

In my iOS application, I start from the very beginning with several pthreads from C ++ code. To make sure the application behaves correctly, according to the document above, I create a fake NSThread that does nothing. I don’t like creating such useless code (usually WTF when you first read it), and I want not to. Is there a better way to host my application in multi-threaded mode?

+6
source share
1 answer

If there is, it is not publicly available and may be unstable.

If you press WTF in your code, rename and replay it to make sense. Since you need a dummy object using a dummy selector, you can simply add a throwaway class, such as CocoaMultithreading , and then send the message +beginMultithreading :

 @interface CocoaMultithreading : NSObject + (void)beginMultithreading; @end int main(void) { [CocoaMultithreading beginMultithreading]; /* now do whatever you want */ return EXIT_SUCCESS; } @implementation CocoaMultithreading + (void)dummyThread:(id)unused { (void)unused; } + (void)beginMultithreading { [NSThread detachNewThreadSelector:@selector(dummyThread:) toTarget:self withObject:nil]; } @end 

This should be fairly explicit.

ETA: Alexander Staubo points out that with OS X 10.5 / iOS 2.0 you can directly call the -start method on NSThread , so the easiest way to flip Cocoa multithreading would be:

 void XXXActivateCocoaMultithreading(void) { [[NSThread new] start]; } 

Then in your main function:

 XXXActivateCocoaMultithreading(); 

This is obvious, but much less erratic. ( XXX there to remind you of the prefixes of non-static functions. Since static functions often become unsteady at some point, prefixing them all from the beginning is a good move.)

+3
source

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


All Articles