Search code examples
arraysswiftgrand-central-dispatchnsdata

Array corrupt on dispatch_barrier_sync


I have 2 function that append data to Array and a function to process it. I use dispatch_barrier_sync to prevent other function to change the data while I process it.

inside append function:

autoreleasepool {  
            dispatch_barrier_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self] () -> Void in             
                self?.bufferVector_.append(data)  
            }  
        }

inside process function:

autoreleasepool {  
            dispatch_barrier_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self] in  
                let len = self!.bufferVector_.count  

                if len > numToExtract {  

                    isMoreInBuffer = true  
                }  

                for bufferData in self!.bufferVector_ {  

                    datas.append(bufferData)  

                    cnt += 1  

                    if cnt == numToExtract {  

                        break;  
                    }  
                }  

                self!.bufferVector_.removeRange(Range(start: 0, end: cnt))  
            }  
        }  

In above function, bufferVector is array of NSData ( [NSData] )

The function work fine, it just after a while it seem the NSData inside the array is corrupted and I receive EXC_BAD_ACCESS

This is what is show when I try to view bufferVector contents from debugger

bufferVector_ = ([NSData]) 8 values  
     [0] = (NSData) 98 bytes  
     [1] = (NSData) 0x16595320  
     [2] = (NSData) 52 bytes  
     [3] = (NSData) 52 bytes  

I can say it is corrupted because the NSData show memory address instead on bytes length

Cheers


Solution

  • You can't apply a barrier to a global queue:

    The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_sync function.