Programming: Threads: Difference between revisions
No edit summary |
|||
Line 33: | Line 33: | ||
* only sharing immutable state | * only sharing immutable state | ||
* synchronization between threads | * synchronization between threads | ||
Unless you are performance constrained, it is safest to pass duplicates of objects rather than references. | |||
</blockquote><!-- Strategies --> | </blockquote><!-- Strategies --> | ||
Revision as of 20:46, 6 August 2022
Threads are units of synchronous code that can be multiplexed within a process.
Threads belonging to the same process, and share the same memory, so care needs to be taken to ensure the same object is not changed twice.
Documentation
wikipedia: thread https://en.wikipedia.org/wiki/Thread_(computing)
Components
Heap
Affinity
Thread Safety
Strategies
Thread safety can be achieved by
- not sharing state across threads (ex. serialization)
- only sharing immutable state
- synchronization between threads
Unless you are performance constrained, it is safest to pass duplicates of objects rather than references.
Atomicity
When an operation occurs on a resource in a concurrent system,
it is considered atomic when access to the item is blocked while it is being modified.
It should not be read, or mutated while it is undergoing mutation.the following are particularly prone to atomicity issues:
- memoization/late binding
- read-then-write operations
- modifying multiple related variables (atomic individually or not)
intrinsic locks are one solution for this.
blocks of code executed while a lock is acquired, like a database transaction,
or Qt's mutexes that are allocated on the stack, and released on object destruction.