Programming: Threads: Difference between revisions

From wikinotes
Line 54: Line 54:


= Shared Memory =
= Shared Memory =
<blockquote>
== Synchronized Primitives ==
<blockquote>
<blockquote>
Some languages may provide safer ways of sharing memory.
Some languages may provide safer ways of sharing memory.
Line 59: Line 61:
* atomic types generally guarantee a read/write to it's value is protected
* atomic types generally guarantee a read/write to it's value is protected
* volatile types generally ensure the value is up to date between threads (no caching). but does not protect getting/setting the variable.
* volatile types generally ensure the value is up to date between threads (no caching). but does not protect getting/setting the variable.
</blockquote><!-- Synchronized Primitives -->
== Strategies ==
<blockquote>
* Confined to thread (thread/object local)
* Shared/Read-Only (constants never written to)
* Synchronized accessed with internally or externally managed locks
</blockquote><!-- Strategies -->
</blockquote><!-- Shared Memory -->
</blockquote><!-- Shared Memory -->

Revision as of 21:13, 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

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 (ex. package attributes)
  • 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.

Shared Memory

Synchronized Primitives

Some languages may provide safer ways of sharing memory.

  • atomic types generally guarantee a read/write to it's value is protected
  • volatile types generally ensure the value is up to date between threads (no caching). but does not protect getting/setting the variable.

Strategies

  • Confined to thread (thread/object local)
  • Shared/Read-Only (constants never written to)
  • Synchronized accessed with internally or externally managed locks