Validity of Pointer Returned by withUnsafePointer During CPU Time Slicing

Hello,

I am using the withUnsafePointer API in Swift and have a question regarding the validity of the pointer returned by this API. Specifically, I want to understand if the pointer remains valid if the CPU performs a context switch due to its time-slicing mechanism while the closure is executing.

Is the pointer returned by withUnsafePointer guaranteed to be valid throughout the entire execution of the closure, even if a CPU context switch occurs as part of time slicing?

Answered by endecotp in 802170022

Context switches are not important here because modern devices all have multi-core processors. It doesn't need a context switch to allow another thread to modify memory, because another thread running concurrently on another core could modify memory.

Regarding withUnsafePointer, I believe the pointed-to memory won't change unexpectedly; you would need to go out of your way to cause another thread to modify the object. I'm not an expert on Swift concurrency, but I'd like to think this should be difficult to get wrong.

Context switches are not important here because modern devices all have multi-core processors. It doesn't need a context switch to allow another thread to modify memory, because another thread running concurrently on another core could modify memory.

Regarding withUnsafePointer, I believe the pointed-to memory won't change unexpectedly; you would need to go out of your way to cause another thread to modify the object. I'm not an expert on Swift concurrency, but I'd like to think this should be difficult to get wrong.

Accepted Answer

Is the pointer … guaranteed to be valid throughout the entire execution of the closure, even if a CPU context switch occurs as part of time slicing?

Yes. Two comments:

  • As endecotp mentioned, context switching is only part of the concern; with multi-core CPUs you have true parallelism in play.

  • This is an unsafe pointer, so the guarantee only applies as long as everyone follows the rules. For example, if one of your thread converts the unsafe pointer to an unsafe mutable pointer and then starts modifying the buffer, bad things could happen to another thread that’s just reading the buffer.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Validity of Pointer Returned by withUnsafePointer During CPU Time Slicing
 
 
Q