File tree Expand file tree Collapse file tree 1 file changed +19
-12
lines changed
TSPL.docc/ReferenceManual Expand file tree Collapse file tree 1 file changed +19
-12
lines changed Original file line number Diff line number Diff line change @@ -248,21 +248,28 @@ including important milestones.
248
248
}
249
249
```
250
250
251
- If you can guarantee that your code uses a potentially unsafe symbol in a safe way ,
252
- You can wrap it in a function and call that function
251
+ If you can guarantee that your code uses a potentially unsafe symbol in a safe manner ,
252
+ You can wrap it in a synchronous function and call that function
253
253
from an asynchronous context.
254
254
255
255
``` swift
256
- // Using a wrapper ensures the mutex is locked
257
- // and unlocked on the same thread.
258
- func modifyProtectedData () -> Int {
259
- var mutex = pthread_mutex_t ()
260
-
261
- mutex.lock ()
262
- count += 1
263
- mutex.unlock ()
264
-
265
- return count
256
+
257
+ // Provide a synchronous wrapper around methods with a noasync declaration.
258
+ extension pthread_mutex_t {
259
+ mutating func withLock (_ op : () -> ()) {
260
+ self .lock ()
261
+ op ()
262
+ self .unlock ()
263
+ }
264
+ }
265
+
266
+ func downloadAndStore (key : Int ,
267
+ dataStore : MyKeyedStorage,
268
+ dataLock : inout pthread_mutex_t) async {
269
+ // Safely call the wrapper in an asynchronous context.
270
+ dataLock.withLock {
271
+ dataStore[key] = downloadContent ()
272
+ }
266
273
}
267
274
```
268
275
You can’t perform that action at this time.
0 commit comments