inout paremeter and thread safety

I’ve run in a hard to track craskh. After some investigation, I think it is related to the use of inout parameter in a thread.

 

I’ll try to explain:

 

class myClass : NSObject {

     var aVar : aStruct

     func myFunc(param: inout aStruct) {
     }

     func calling() {
          myFunc(param: &aVar)
     }
}



 

When I call this func from another thread, I get random crashes (BAD_ACCESS).

 

I understand it is not safe to pass address in a thread.

So I try to change like this:

 

     func calling() {
          var localVar = aVar
          myFunc(param: &localVar)
          aVar = localVar
     }



 

That seems to solve the crash, but is that a correct implementation ?

 

So, is iy thread safe to call

     myFunc(param: &localVar)

if localVar is declared in the function ?

 

This is a serious limit to the use of inout (be careful if the func is to be called from another thread) and I find it really poorly documented (I’ve found no reference to this in Swift language). Is it detailed somewhere ?

 

Edited : Note. I feel the crash are much more frequent after I switched to Swit 3 and 4. Is there any reason for that or just an impression ?

Powered by WPeMatico

About

You may also like...

Comments are closed.