Interlocked operations in iOS?

2020-03-01 08:00发布

Are there interlocked(atomic) operations in iOS SDK?

I need interlocked increment\decrement and interlocked comparsion.

*UPDATE: * My main problem is waiting for few NSThreads created by main thread(main thread mustn't work while other threads work).

I don't know how to do it.

4条回答
不美不萌又怎样
2楼-- · 2020-03-01 08:22

Update: Language level atomics under C11 and C++11 are now available.

You can simply declare _Atomic(int) a;.

A more detailed introduction.


atomic operations and their documentation can be found in libkern/OSAtomic.h. an overview can be found under man atomic.

as well, you will likely find C11 and C++11 language/library support very soon.

查看更多
狗以群分
3楼-- · 2020-03-01 08:27

Objective-C has the keyword synchronized for atomic operations.

@synchronized(object) {
    // ...
}

If you specify the attribute atomic in a property declaration, the setters and getters will be sythesized using these synchronized-blocks.

Also look at NSLock and NSLocking protocol.

查看更多
太酷不给撩
4楼-- · 2020-03-01 08:33

You can use the OSAtomicIncrement*/OSAtomicDecrement* operations described in Using Atomic Operations.

查看更多
▲ chillily
5楼-- · 2020-03-01 08:36

You can take a look at the properties (ObjectiveC 2.0 feature).

@property int atomicProperty;

There is in fact no 'atomic' specifier, as properties default to atomic. They can be set to 'nonatomic'.

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html

You may be interested by @synchronized also. Or this part of the doc:

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html

查看更多
登录 后发表回答