Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a thread [closed]

I have been looking online at what a thread is and I do not feel like I understand it. Could someone shed some light on this? In terms of programming languages for relating to C++, objective-C would be nice.

In objective-c, I encountered

@property(nonatomic, strong) NSString *name;

the explanation for nonatomic was it means to not be worried about multiple threads trying to access the object at the same time, and objective-c does not have to synthesize thread safe code. So what does that exactly mean as well.

like image 869
Masterminder Avatar asked Dec 04 '25 06:12

Masterminder


1 Answers

A process can consist of multiple threads of execution, which logically can be thought of as running simultaneously alongside each other. Each thread runs independently but shares the same memory and process state. A single thread can "do one thing": perform computation, interact with the network, update a UI, decode a video, etc. But, a single thread cannot do all of these at once without a significant amount of extra work from the programmer. Having multiple threads in a process enables the programmer to easily enable an application to do multiple things at once (multitasking).

Using multiple threads does introduce some new challenges, though. For example, if you have two threads that access the same variable, you can end up with a concurrency hazard in which the variable might not be completely updated by one thread before the other thread accesses it, leading to failures in the program. Objective-C will generate thread-safe code by default, to avoid this situation. nonatomic tells the compiler that you will never access it from multiple threads simultaneously, so the compiler can skip the thread-safe code and make faster code. This can be useful if you are going to supply your own synchronization, anyway (e.g. to keep a group of properties in sync, which Objective-C itself cannot help you with).

If you violate the core nonatomic assumption and access a nonatomic variable from multiple threads at the same time, all hell will break loose.

like image 99
nneonneo Avatar answered Dec 06 '25 20:12

nneonneo