discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: does method invocation involve a lock?


From: David Chisnall
Subject: Re: does method invocation involve a lock?
Date: Fri, 21 Sep 2018 16:26:32 +0100
User-agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Thunderbird/60.0

On 21/09/2018 15:49, Tom Sheffler wrote:
This question is for my own research: I’m curious about whether invoking [obj 
method] can block.  If obj is allocated, and method is simple, does method 
invocation involve a lock.

If obj is allocated, obj has not had its isa pointer swizzled to a class that has not received any messages, and the class of obj implements the method, then no, the message send itself will not block.

Message sends in the fast path just look up the implementation in the dtable and jump there. If the method does not exist, then the first check will see if there is a dtable for the class (dtables are lazily allocated on first message send to the class or an instance of the class). If there isn't one, then the runtime will try to allocate one and may need to send a +initialize message to the object.

The +initialize message guarantees that no messages will be sent to the class or its instances from any other thread until the +initialize method has returned. This gets quite exciting inside the runtime if +initialize throws an exception. This atomicity guarantee is important for implementing singletons, because it means that you can have a class that has methods like this:

```objc
static Singleton *sharedInstance;
+(void)initialize
{
        sharedInstance = [self new];
}
+(Singleton*)sharedInstance
{
        return sharedInstance;
}
```

There is no locking in the +sharedInstance method and none is required, because the runtime guarantees that +initialize will be called precisely once before any calls to +sharedInstance.

The other situation where locking can occur is if the message send invokes any forwarding mechanisms. For example, with LanguageKit we had a mode where if you sent a message to an object it would pop up a code editor, ask you to provide an implementation of the method, JIT compile it, insert it into the class, and then return the method. This, of course, requires blocking the calling thread and so acquires a lock.

Any of the methods such as -forwardingTargetForSelector: and +instanceMethodForSelector: may acquire locks and can be invoked in between a caller's message send expression and flow control landing in the method implementation.

David



reply via email to

[Prev in Thread] Current Thread [Next in Thread]