NSThread VS pthreads
Asked Answered
H

2

6

What is the difference between NSThread and pthread? Does NSThread use pthread as its internal implementation and do we really need the extra overhead of NSThread when pthreads suffice especially on the iPhone.

Haileyhailfellowwellmet answered 5/12, 2010 at 13:16 Comment(0)
M
9

I don't know for sure if NSThread use pthreads library internally. It probably does, but since we don't have source code for NSThread we really don't know.

The difference is that pthread is a C library and NSThread is an Objective-C library. But they both accomplish the same functionality.

The need for an Objective-C library is if you need to use it in combination with other portions of Objective-C API. I.E., you won't be able to store a pthread in a NSArray.

Misusage answered 5/12, 2010 at 13:24 Comment(2)
NSThread uses pthreads internally AFAIK. Pthreads though could provide more flexible and powerful mechanisms for thread management and synchronization, like wait until another thread finished, etc..Putative
I'm looking at some call stacks from a crash and it's full of pthreads. That wouldn't mean NSThread uses pthread, but this is telling: 6 Foundation __NSThread__start__ + 1024, 7 libsystem_pthread.dylib _pthread_body + 240, 8 libsystem_pthread.dylib _pthread_body + 282, 9 libsystem_pthread.dylib thread_start + 4Undoing
B
1

As far as I know NSThread does not use p-threads, unless Apple has radically changed things. The roots of OOPC were too early for the POSIX standard (pthreads came about in 1c, which was 1995 I think). This is one of many criticisms leveled at current Objective-C runtimes. See http://www.jot.fm/issues/issue_2009_01/article4.pdf You can, however access pthreads in Objective-C through the standard C libraries. We actually had made this assumption in a project and ran into issues when interacting with a library we built using pthreads (this was around run loops with NSNotificationQueue).

Blume answered 14/6, 2012 at 1:0 Comment(2)
I don't know, but it is entirely plausible that NSThread originally used something other than pthreads (e.g. direct use of Mach thread API). But I think it likely that today it actually uses pthreads. Evidence: /System/Library/Frameworks/Foundation.framework/Foundation contains the string "NSThread *_NSThreadGet0(pthread_t)". Looks like an undocumented API to convert a pthread to an NSThread? which implies NSThread is probably just a pthread wrapper (which in turn is just a wrapper for Mach threads)Kachine
I think it uses pthread. See the call stacks I posted to @Pablo's answer.Undoing

© 2022 - 2024 — McMap. All rights reserved.