JLT
JLT

Reputation: 3182

Why There Is No Need To Open A New Thread When Opening A Socket Connection In iOS

Before when I was developing Android apps that are related to socket connections, I always need to open a new Thread to handle them, or else an error will definitely occur.

On the other hand, when I was doing the same thing in iOS apps, there's no need for me to open a new Thread to handle those socket connections, and my UI still runs smoothly. I don't understand why is that happening.

I've done some research but I don't find any source that explains this matter.

Please help me understand this.Thanks in advance!

Upvotes: 0

Views: 119

Answers (1)

Rob Napier
Rob Napier

Reputation: 299585

As @Fonix notes, if you're using GCDAsyncSocket, it's handling concurrency for you. But if you read the GCDAsyncSocket code, you'll notice it never generates any threads either. Almost nothing in iOS ever generates its own thread. References to NSThread are almost always a mistake. iOS concurrency is based on queues and managed by GCD (Grand Central Dispatch). Queues do eventually map to threads, but that's an internal detail, and it's not a 1:1 mapping.

You'll want to read the Concurrency Programming Guide, and particularly "Migrating Away from Threads" in order to understand how iOS manages concurrency. It's radically different than Android, and this misunderstanding often creates a lot of broken iOS code.

Upvotes: 1

Related Questions