1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
//! This belongs in `std` IMO, but wasn't accepted there:
//! <https://github.com/rust-lang/rust/pull/136616>
use fmt;
use PhantomData;
use crateAllocated;
use crate::;
/// Whether the current thread is the main thread.
/// A marker type for functionality only available on the main thread.
///
/// The main thread is a system-level property on Apple/Darwin platforms, and
/// has extra capabilities not available on other threads. This is usually
/// relevant when using native GUI frameworks, where most operations must be
/// done on the main thread.
///
/// This type enables you to manage that capability. By design, it is neither
/// [`Send`] nor [`Sync`], and can only be created on the main thread, meaning
/// that if you have an instance of this, you are guaranteed to be on the main
/// thread / have the "main-thread capability".
///
/// [The `main` function][main-functions] will run on the main thread. This
/// type can also be used with `#![no_main]` or other such cases where Rust is
/// not defining the binary entry point.
///
/// See the following links for more information on main-thread-only APIs:
/// - [Are the Cocoa Frameworks Thread Safe?](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47)
/// - [About Threaded Programming](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html)
/// - [Thread Safety Summary](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-SW1)
/// - [Technical Note TN2028 - Threading Architectures](https://developer.apple.com/library/archive/technotes/tn/tn2028.html#//apple_ref/doc/uid/DTS10003065)
/// - [Thread Management](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html)
/// - [Swift's `@MainActor`](https://developer.apple.com/documentation/swift/mainactor)
/// - [Main Thread Only APIs on OS X](https://www.dribin.org/dave/blog/archives/2009/02/01/main_thread_apis/)
/// - [Mike Ash' article on thread safety](https://www.mikeash.com/pyblog/friday-qa-2009-01-09.html)
///
/// [main-functions]: https://doc.rust-lang.org/reference/crates-and-source-files.html#main-functions
///
///
/// # Main Thread Checker
///
/// Xcode provides a tool called the ["Main Thread Checker"][mtc] which
/// verifies that UI APIs are being used from the correct thread. This is not
/// as principled as `MainThreadMarker`, but is helpful for catching mistakes.
///
/// You can use this tool on macOS by loading `libMainThreadChecker.dylib`
/// into your process using `DYLD_INSERT_LIBRARIES`:
///
/// ```console
/// DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libMainThreadChecker.dylib MTC_RESET_INSERT_LIBRARIES=0 cargo run
/// ```
///
/// If you're not running your binary through Cargo, you can omit
/// [`MTC_RESET_INSERT_LIBRARIES`][mtc-reset].
///
/// ```console
/// DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libMainThreadChecker.dylib target/debug/myapp
/// ```
///
/// If you're developing for iOS, you probably better off enabling the tool in
/// Xcode's own UI.
///
/// See [this excellent blog post][mtc-cfg] for details on further
/// configuration options.
///
/// [mtc]: https://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early#Detect-improper-UI-updates-on-background-threads
/// [mtc-reset]: https://bryce.co/main-thread-checker-configuration/#mtc_reset_insert_libraries
/// [mtc-cfg]: https://bryce.co/main-thread-checker-configuration/
///
///
/// # Examples
///
/// Retrieve the main thread marker in different situations.
///
/// ```
/// use objc2::MainThreadMarker;
///
/// # // explicitly uses `fn main`
/// fn main() {
/// // The thread that `fn main` runs on is the main thread.
/// assert!(MainThreadMarker::new().is_some());
///
/// // Subsequently spawned threads are not the main thread.
/// std::thread::spawn(|| {
/// assert!(MainThreadMarker::new().is_none());
/// }).join().unwrap();
/// }
/// ```
///
/// Use when accessing APIs that are only safe to use on the main thread.
///
/// ```no_run
/// use objc2::MainThreadMarker;
/// # #[cfg(needs_app_kit)]
/// use objc2_app_kit::NSApplication;
/// #
/// # use objc2::runtime::NSObject as NSApplication;
/// # trait Foo {
/// # fn sharedApplication(_mtm: MainThreadMarker) {}
/// # }
/// # impl Foo for NSApplication {}
///
/// # // explicitly uses `fn main`
/// fn main() {
/// // Create a new MainThreadMarker.
/// let mtm = MainThreadMarker::new().expect("must be on the main thread");
///
/// // NSApplication is only usable on the main thread,
/// // so we need to pass the marker as an argument.
/// let app = NSApplication::sharedApplication(mtm);
///
/// // Do something with the application
/// // app.run();
/// }
/// ```
///
/// Create a static that is only usable on the main thread. This is similar to
/// a thread-local, but can be more efficient because it doesn't handle
/// multiple threads.
///
/// See also `dispatch2::MainThreadBound`.
///
/// ```
/// use objc2::MainThreadMarker;
/// use std::cell::UnsafeCell;
///
/// struct SyncUnsafeCell<T>(UnsafeCell<T>);
///
/// unsafe impl<T> Sync for SyncUnsafeCell<T> {}
///
/// static MAIN_THREAD_ONLY_VALUE: SyncUnsafeCell<i32> = SyncUnsafeCell(UnsafeCell::new(0));
///
/// fn set(value: i32, _mtm: MainThreadMarker) {
/// // SAFETY: We have an instance of `MainThreadMarker`, so we know that
/// // we're running on the main thread (and thus do not need any
/// // synchronization, since the only accesses to this value is from the
/// // main thread).
/// unsafe { *MAIN_THREAD_ONLY_VALUE.0.get() = value };
/// }
///
/// fn get(_mtm: MainThreadMarker) -> i32 {
/// // SAFETY: Same as above.
/// unsafe { *MAIN_THREAD_ONLY_VALUE.0.get() }
/// }
///
/// # // explicitly uses `fn main`
/// fn main() {
/// let mtm = MainThreadMarker::new().expect("must be on the main thread");
/// set(42, mtm);
/// assert_eq!(get(mtm), 42);
/// }
/// ```
// ^^^^ this is valid because it's still `!Send` and `!Sync`.
/// Get a [`MainThreadMarker`] from a main-thread-only object.
///
/// This is a shorthand for [`MainThreadOnly::mtm`].