<p>I am working on a cocoa software and in order to keep the GUI responsive during a massive data import (Core Data) I need to run the import outside the main thread.</p>

<p>Is it safe to access those objects even if I created them in the main thread without using locks <strong>if</strong> I don't explicitly access those objects while the thread is running.</p>

[{'answer_id': 67203, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 0, 'selected': False, 'text': "<p>The whole point of using locks is to ensure that two threads don't try to access the same resource.  If you can guarantee that through some other mechanism, go for it.</p>\n"}, {'answer_id': 67230, 'author': 'Alexandre Brasil', 'author_id': 8841, 'author_profile': 'https://Stackoverflow.com/users/8841', 'pm_score': 0, 'selected': False, 'text': "<p>Even if it's safe, but it's not the best practice to use shared data between threads without synchronizing the access to those fields. It doesn't matter which thread created the object, but if more than one line of execution (thread/process) is accessing the object at the same time, since it can lead to data inconsistency.</p>\n\n<p>If you're absolutely sure that only one thread will ever access this object, than it'd be safe to not synchronize the access. Even then, I'd rather put synchronization in my code now than wait till later when a change in the application puts a second thread sharing the same data without concern about synchronizing access.</p>\n"}, {'answer_id': 67263, 'author': 'Tim Frey', 'author_id': 1471, 'author_profile': 'https://Stackoverflow.com/users/1471', 'pm_score': 0, 'selected': False, 'text': '<p>Yes, it\'s safe.  A pretty common pattern is to create an object, then add it to a queue or some other collection.  A second "consumer" thread takes items from the queue and does something with them.  Here, you\'d need to synchronize the queue but not the objects that are added to the queue.</p>\n\n<p>It\'s NOT a good idea to just synchronize everything and hope for the best.  You will need to think very carefully about your design and exactly which threads can act upon your objects.</p>\n'}, {'answer_id': 67271, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 0, 'selected': False, 'text': '<p>Yes you can do it, it will be safe</p>\n\n<p>... \nuntil the second programmer comes around and does not understand the same assumptions you have made. That second (or 3rd, 4th, 5th, ...) programmer is likely to start using the object in a non safe way (in the creator thread). The problems caused could be very subtle and difficult to track down. For that reason alone, and because its so tempting to use this object in multiple threads, I would make the object thread safe.</p>\n\n<p>To clarify, (thanks to those who left comments):</p>\n\n<p>By "thread safe" I mean programatically devising a scheme to avoid threading issues. I don\'t necessarily mean devise a locking scheme around your object. You could find a way in your language to make it illegal (or very hard) to use the object in the creator thread. For example, limiting the scope, in the creator thread, to the block of code that creates the object. Once created, pass the object over to the user thread, making sure that the creator thread no longer has a reference to it.</p>\n\n<p>For example, in C++</p>\n\n<pre><code>void CreateObject()\n{\n    Object* sharedObj = new Object();\n    PassObjectToUsingThread( sharedObj); // this function would be system dependent\n}\n</code></pre>\n\n<p>Then in your creating thread, you no longer have access to the object after its creation, responsibility is passed to the using thread.</p>\n'}, {'answer_id': 67318, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 0, 'selected': False, 'text': '<p>Two things to consider are:</p>\n\n<ul>\n<li>You must be able to guarantee that the object is fully created and initialised before it is made available to other threads.</li>\n<li>There must be some mechanism by which the main (GUI) thread detects that the data has been loaded and all is well. To be thread safe this will inevitably involve locking of some kind.</li>\n</ul>\n'}, {'answer_id': 67965, 'author': 'Barry Wark', 'author_id': 2140, 'author_profile': 'https://Stackoverflow.com/users/2140', 'pm_score': 1, 'selected': False, 'text': '<p>I believe that this is <strong>not</strong> safe to do with NSManagedObjects (or subclasses) that are managed by a CoreData NSManagedObjectContext. In general, CoreData may do many tricky things with the sate of managed objects, including firing faults related to those objects in separate threads. In particular, <code>[NSManagedObject initWithEntity:insertIntoManagedObjectContext:]</code> (the designated initializer for NSManagedObjects as of OS X 10.5), does not guarantee that the returned object is safe to pass to an other thread.</p>\n\n<p>Using CoreData with multiple threads is well documented on Apple\'s <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CoreData/Articles/cdMultiThreading.html" rel="nofollow noreferrer">dev site</a>. </p>\n'}, {'answer_id': 68237, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 3, 'selected': True, 'text': '<p>With Core Data, you should have a separate managed object context to use for your import thread, connected to the same coordinator and persistent store.  You cannot simply throw objects created in a context used by the main thread into another thread and expect them to work.  Furthermore, you cannot do your own locking for this; you must at minimum lock the managed object context the objects are in, as appropriate.  But if those objects are bound to by your views a controls, there are no "hooks" that you can add that locking of the context to.</p>\n\n<p>There\'s no free lunch.</p>\n\n<p>Ben Trumbull explains some of the reasons why you need to use a separate context, and why "just reading" isn\'t as simple or as safe as you might think, in <a href="http://lists.apple.com/archives/webobjects-dev/2004/Dec/msg00255.html" rel="nofollow noreferrer" title="Re: locking problem">this great post from late 2004 on the webobjects-dev list</a>.  (The whole thread is great.)  He\'s discussing the Enterprise Objects Framework and WebObjects, but his advice is fully applicable to Core Data as well.  Just replace "EC" with "NSManagedObjectContext" and "EOF" with "Core Data" in the meat of his message.</p>\n\n<p>The solution to the problem of sharing data between threads in Core Data, like the Enterprise Objects Framework before it, is "don\'t."  If you\'ve thought about it further and you really, honestly do have to share data between threads, then the solution is to keep independent object graphs in thread-isolated contexts, and use the information in the save notification from one context to tell the other context what to re-fetch.  <a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/Reference/Reference.html#//apple_ref/occ/instm/NSManagedObjectContext/refreshObject:mergeChanges:" rel="nofollow noreferrer" title="-[NSManagedObjectContext refreshObject:mergeChanges:]"><code>-[NSManagedObjectContext refreshObject:mergeChanges:]</code></a> is specifically designed to support this use.</p>\n'}]
['https://Stackoverflow.com/questions/67154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407138/']