What is the best place to start a new thread? Should I create it in the Application Delegate, or can I start it from any other class for example a singleton?
Thanks for your help
if you're joining the thread, then you will typically want to create the thread local (or accessible to) the creation site, or in the same object's implementation. you'll usually join or use a task based interface when you want execution of the current thread to block until the threads/tasks complete.
if detaching (likely if you alloc an NSThread or use a detach... call), then it may be created wherever it makes the most sense in your program's flow.
That means you should favor 'local' as opposed to centralized in both cases.
If you use a task based interface (e.g. NSOperation), then you may need to centralize some things so many clients may reach an operation queue (as an example).
extracting detail from the comments: if you create a detached thread to interact with a server, then it is likely a good idea to create the thread in your implementation which interacts with the server, or the client code that interacts with those implementations. The app delegate is not a good choice when the cause/effect does not need to be centralized.
Related
For my macOS application, I'd like to use concurrent map and queue data structure to be shared between multithread process and support parallel operations.
After some research I've found what what I need, but unfortunately those are only implemented in windows.
concurrency::concurrent_unordered_map<key,value> concurrency::concurrent_queue<key>
Perhaps there are synonyms internal implementations in macOS in CoreFoundation or other framework that comes with Xcode SDK (disregarding the language implementation) ?
thanks,
Perhaps there are synonyms internal implementations in macOS in CoreFoundation or other framework that comes with Xcode SDK (disregarding the language implementation) ?
Nope. You must roll-your-own or source elsewhere.
The Apple provided collections are not thread safe, however the common recommendation is to combine them with Grand Central Dispatch (GCD) to provide lightweight thread-safe wrappers, and this is quite easy to do.
Here is an outline of one way to do it for NSMutableDictionary, which you would use for your concurrent map:
Write a subclass, say ThreadSafeDictionary, of NSMutabableDictionary. This will allow your thread safe version to be passed anywhere an NSMutableDictionary is accepted.
The subclass should have a private instance of a standard NSMutableDictionary, say actualDictionary
To subclass NSMutableDicitonary you just need to override 2 methods from NSMutableDictionary and 4 methods from NSDictionary. Each of these methods should invoke the same method on actualDictionary after meeting any concurrency requirements.
To handle concurrency requirements the subclass should first create a private concurrent dispatch queue using dispatch_queue_create() and save this in an instance variable, say operationQueue.
For operations which read from the dictionary the override method uses a dispatch_sync() to schedule the read on actualDicitonary and return the value. As operationQueue is concurrent this allows multiple concurrent readers.
For operations which write to the dictionary the override method uses a dispatch_async_barrier() to schedule the write on actualDicitonary. The async means the writer is allowed to continue without waiting for any other writers, and the barrier ensures there are no other concurrent operations mutating the dictionary.
You repeat the above outline to implement the concurrent queue based on one of the other collection types.
If after studying the documentation you get stuck on the design or implementation ask a new question, show what you have, describe the issue, include a link back to this question so people can follow the thread, and someone will undoubtedly help you take the next step.
HTH
In my application, I have to display image files as a list in tableview, present them in full size and as multiple thumbnails. Hence basically I developed three seperate classes to handle these three views. Now to perform any file operations, I can think of two approaches:
Create appdelegate objects for all these classes, handle them accordingly. When one operation on a photo file is performed in one class, all other classes are notified using NSNotification, keeping the obeserver as Appdelegate object.
Create locally objects for these classes as and when required and assign delegates for performing file operations from one class to other by calling relevant methods.
However, I was not able to judge Which approach would be better in terms of memory usage and performance? Thanks in advance.
Using a one-to-one relationship with direct messaging is the simpler relationship and means of communication/messaging. Favor the delegate callback -- Number 2.
It is also easy to make this design bidirectional -- if the view goes offscreen, you could perform a cancellation. If the load fails, it is easier to inform the controller.
NSNotifications are comparably heavyweight. Not necessary.
Storing a bunch of stuff in a singleton (app delegate) can result in several unnecessarily retained objects. If your program is concurrent, then that can add even more complexity. There's no need for any of this complexity or introduction of mutable global state, and there is no reason presented whereby the objects should have a much larger scope of access and lifetime.
You can optimize for specific needs beyond that, but I don't see any at this time.
It depends a lot on the code and how you are structuring your app. I general use delegates in the following situation:
Where the delegate object exists before and after the main object that needs it. In other words the main object does not need to worry about the lifecycle of it's delegate.
Where the relationship between an object and it's delegate object is a strict one to one. In other words only one delegate object needs to interact with the main object. I have seen situations where delegates are swapped in and out and I would not recommend such code.
Where the main object needs information from the delegate.
I would use notifications where:
Multiple objects need to know of about things happening in another class.
Where the main class does not need to interact with the other classes or even know they exist.
Which ever you choose I would not have more than one file management object for each image. The simple reason being that having multiple means you need to ensure that they all have the same state and therefore are communicating with each other. Otherwise bugs will creep in.
As the question states, can a shared method of an object be multithreaded? I don't quite having threading down in my skillset, otherwise I would test myself. On the other hand, I am involved in designing class that could be part of a multithreaded application in VB.Net.
If you mean "is it safe for a shared method to be called from multiple threads at once" - the answer is "it depends". A method itself isn't multi-threaded or single-threaded; threads and methods are very separate things.
If your shared method is called from multiple threads, then unless there's any synchronization to say otherwise, it will be executed concurrently on those threads. That can definitely cause a problem if your method uses shared state without appropriate safeguards. However, if the method either takes care when accessing shared resources (e.g. using locks) or it doesn't access any state which is shared between threads, that's fine.
Yes, it can. Any method can become a thread.
Yes, shared methods can be executed simultaneously by multiple threads. In fact, they often are. You do not have as much control over which threads are executing shared methods as compared to instance methods. Consider an ASP.NET application for example. Different page requests may come in on different threads. If you call a shared method in your web application then there is a high probability that it is getting executed by multiple threads.
This is an incredibly important point when designing an API. All self respecting API authors go to extremes to make sure all shared/static methods are thread-safe. Afterall, it would be ridiculously onerous to make a caller of your API synchronize access to every single shared/static method you provide. Take a look at the documentation Microsoft provides for almost all classes in the BCL.
Any public static (Shared in Visual Basic) members of this type are
thread safe. Any instance members are not guaranteed to be thread
safe.
I have yet to run across a static method provided by Microsoft that was not thread-safe.1 And that is good because it makes life easier for you and I.
1If you know of one let me know.
There are certain places in my code where I invoke an activity using the WorkflowInvoker.Invoke method. I'm having a lot of performance issues because I create an activity every time I need to invoke this.
According this MSDN Blog post, I should cache the activity and run the same activity instance rather than creating a new one.
However, my application is multi-threaded. Would it be safe for many threads to use the same instance of the Activity? According to the MSDN documentation, it says its not thread-safe, but it looks like the standard message for almost all classes.
I suspect that it should be thread-safe, since the data that the activity uses is stored in a separate context (as Variables and Arguments) rather than a normal instance member of the activity class.
I have found no problems with threads sharing the same Activity instance. This makes sense because data is passed into the activity through the context (rather than the properties of the Activity object). Activity caching significantly improves performance.
Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?
Additional question: normally when should we go for the singleton pattern and when should we avoid it?
Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.
Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.
In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.
Good luck!
The general rule of thumb i use for Singletons is that it should not affect the running code, and have no side-effects. Essentially for me, in my projects this translates into some kind of logging functionality, or static value lookup (ie. loading some common data from a database once and storing it for reference so it doesn't have to be read in everytime its needed).
A singleton is no different than any other object other than there is only one instance. What happens when you try to access it will largely depend on what the accessing threads are attempting (ie read vs write) and what kind of data your singleton is holding.
The answer to your question as it is, is "it really depends". What kind of singleton? i.e. what does it do, and how does it do it? And in what language?
The reality is that the singleton patter)n only dictates and enforces that you can only have one instance of a certain object. In of itself it does not say anything about multiple threads accessing that object.
So, if coded right (with thread synchronization implemented correctly) there is no reason why it shouldn't behave correctly - even if the requests to the object take a really long time to process!
Then you need thread safe implementation of singleton pattern.
Find this article useful for the same which describes most of the multi-threading scenario of singleton pattern.
HTH!