AFNetworking/AFNetworking — pull request #935 by OliverLetterer (2013-04-21 16:19:49+00:00)
Title: Workaround for #907.

I can reproduce issue #907 with [this sample project](https://fdaaf4cf-a-62cb3a1a-s-sites.googlegroups.com/site/aledvx/demo_iReport.zip?attachauth=ANoY7cqcDMl230Rsye5ho9KF0LHigRpbWZNCmMOntWU4twjGyhf9MgxK1cal46uHKQ0TpZIeazvEX_k89nJXx2vel9t7zJ4jwPeF0y7Fje4uIk34obutPfZM8SaILnc6dmpsB_gBvs6W34ZAp9kfamWCvPDFnn1F8_LIKSO8IAuJTACtx4ykXVOVovocaXcqeEYN70uTKgTJwKe9A500G4BFz2ehovNseg%3D%3D&attredirects=0) and I think there is a race condition in [CFStream.c](http://www.opensource.apple.com/source/CF/CF-744.18/CFStream.c) in

```c
static CFArrayRef _CFStreamCopyRunLoopsAndModes(struct _CFStream *stream)
{
CFArrayRef result = NULL;
if (stream && stream->client) {
_CFStreamLock(stream);
if (stream->client->runLoopsAndModes) {
result = CFArrayCreateCopy(CFGetAllocator(stream), stream->client->runLoopsAndModes);
}
checkRLMArray(result);
_CFStreamUnlock(stream);
}
return result;
}
```

The outputStream of an `AFMultipartBodyStreamProvider` is being deallocated on the main thread while its being used on the NSURLConnectionLoader thread. I think the events of the race condition are as follows:

* The first if statement `stream && stream->client` is being checked on the NSURLConnectionLoader thread
* The output stream is being deallocated on the main thread
* Then the lock in `_CFStreamCopyRunLoopsAndModes` is being acquired and somewhere in `CFArrayCreateCopy` I get a zombie message in the console.

Therefore, Im keeping the output stream in `-[AFMultipartBodyStreamProvider close]` alive for just a little longer. A simple `dispatch_async(dispatch_get_main_queue(), ...);` wouldn't be enough because I checked and the actual deallocation of the output stream is already being done in the next runloop iteration on the main thread.

With this workaround, I hammered the refresh button in the above sample app for almost 10 minutes and for me, the workaround seems to be working.