q2K BHP
Black History Portal
THE BHP WIRE —
HIDDEN TRUTHS
What's New!
THE JOURNEY THROUGH TIME

Explore Black History

Explore the people, places, events, achievements, struggles and stories that shaped our journey.

✊🏾

Civil Rights

Movements, leaders, victories and the continuing fight for equality.

⚙️

Black Inventors

Innovation, patents, science, technology and world-changing contributions.

🏆

Sports

Pioneers, champions, Negro Leagues, records, activism and excellence.

♟️

People

Meet the people whose lives, choices and achievements shaped the journey.

📍

Places

Black towns, communities, institutions and places where history happened.

📜

Events

Moments that changed communities, movements, institutions and the nation.

Enter a person, place, event, or topic.
MY'STORY

The MOVE Fire

This is a personal recollection on the Move fire on May 13, 1985 Philadelphia police fired thousands of rounds at the MOVE house, city officials approved dropping an explosive device on the roof, the resulting fire was allowed to burn, 11 people—including five children—died, and 61 homes were destroyed. Philadelphia City Council later called it a “brutal attack carried out by the City of Philadelphia on its own citizens” and acknowledged that no individual faced criminal consequences for the bombing. One timeline correction worth preserving for the BHP record: the major previous MOVE-police confrontation was August 8, 1978, about seven years before the bombing, not a year or two earlier. Officer James Ramp was killed, other police and firefighters were wounded, nine MOVE members were later convicted, and television cameras recorded police beating Delbert Africa during his arrest. The 1985 MOVE Commission later specifically criticized city planners for failing to adequately use lessons from that 1978 confrontation. And that actually strengthens the point you’re making: 1985 did not happen without precedent or institutional memory. There had already been a deadly confrontation with MOVE, years of conflict, negotiations and police involvement before Osage Avenue.

MORE →
BLACK FACTS
The Truths They Never Taught You...

Katherine Johnson — Mathematics to the Moon

Katherine Johnson’s mathematical calculations helped guide some of America’s most important early space missions while she confronted the racial and gender barriers faced by Black women in twentieth-century America.

MORE →
BHP gathered finds from its connected research sources. Showing the 4 strongest Black History matches.
← BACK TO RESULTS
Wikipedia

Thread-local storage

In computer programming, thread-local storage (TLS) is a memory management method that uses static or global memory local to a thread. The concept allows storage of data that appears to be global in a system with separate threads.

Many systems impose restrictions on the size of the thread-local memory block, in fact often rather tight limits. On the other hand, if a system can provide at least a memory address (pointer) sized variable thread-local, then this allows the use of arbitrarily sized memory blocks in a thread-local manner, by allocating such a memory block dynamically and storing the memory address of that block in the thread-local variable. On RISC machines, the calling convention often reserves a thread pointer register for this use.

Usage

[edit]

While the use of global variables is generally discouraged in modern programming, some older operating systems such as UNIX were originally designed for uniprocessor hardware and often use global variables to store important values. An example is the errno used by many functions of the C library. On a modern machine, where multiple threads may be modifying the errno variable, a call of a system function on one thread may overwrite the value previously set by a call of a system function on a different thread, possibly before following code on that different thread could check for the error condition. The solution is to have errno be a variable that looks as if it is global, but is physically stored in a per-thread memory pool, the thread-local storage.

A second use case would be multiple threads accumulating information into a global variable. To avoid a race condition, every access to this global variable would have to be protected by a mutex. Instead, each thread might accumulate into a thread-local variable, thereby eliminating any possibility of a race condition, thereby removing the need for locking. The threads then only have to synchronise a final accumulation from their own thread-local variable into a single global variable.

Windows implementation

[edit]

The application programming interface (API) function TlsAlloc can be used to obtain an unused TLS slot index; the TLS slot index will then be considered 'used'.

The TlsGetValue and TlsSetValue functions are then used to read and write a memory address to a thread-local variable identified by the TLS slot index. TlsSetValue only affects the variable for the current thread. The TlsFree function can be called to release the TLS slot index.

There is a Win32 Thread Information Block for each thread. One of the entries in this block is the thread-local storage table for that thread.[1] Each call of TlsAlloc returns a unique index into this table. Each thread can independently use TlsSetValue(index, value) and obtain the specified value via TlsGetValue(index), because these set and look up an entry in the thread's own table.

Apart from TlsXxx function family, Windows executables can define a section which is mapped to a different page for each thread of the executing process. Unlike TlsXxx values, these pages can contain arbitrary and valid addresses. These addresses, however, are different for each executing thread and therefore should not be passed to asynchronous functions (which may execute in a different thread) or otherwise passed to code which assume that a virtual address is unique within the whole process. TLS sections are managed using memory paging and its size is quantized to a page size (4kB on x86 machines). Such sections may only be defined inside a main executable of a program - DLLs should not contain such sections, because they are not correctly initialized when loading with LoadLibrary.

Pthreads implementation

[edit]

In the Pthreads API, memory local to a thread is designated with the term Thread-specific data.

The functions pthread_key_create and pthread_key_delete are used respectively to create and delete a key for thread-specific data. The type of the key is explicitly left opaque and is referred to as pthread_key_t. This key can be seen by all threads. In each thread, the key can be associated with thread-specific data via pthread_setspecific. The data can later be retrieved using pthread_getspecific.

In addition pthread_key_create can optionally accept a destructor function that will automatically be called at thread exit, if the thread-specific data is not NULL. The destructor receives the value associated with the key as parameter so it can perform cleanup actions (close connections, free memory, etc.). Even when a destructor is specified, the program must still call pthread_key_delete to free the thread-specific data at process level (the destructor only frees the data local to the thread).

Language-specific implementation

[edit]

Apart from relying on programmers to call the appropriate API functions, it is also possible to extend the programming language to support thread local storage (TLS).

C and C++

[edit]

In C11, the keyword _Thread_local is used for defining thread-local variables. The header <threads.h>, if supported, defines thread_local as a synonym for that keyword.

In C11, <threads.h> also defines a number of functions for retrieving, changing, and destructing a thread-local storage, using names starting with tss_. In C23, thread_local itself becomes a keyword.[2]

thread_local int foo = 0;

C++11 introduces the thread_local[3] keyword which can be used in the following cases

  • Namespace level (global) variables
  • File static variables
  • Function static variables
  • Static member variables

Aside from that, various compiler implementations provide specific ways to declare thread-local variables:

On Windows versions before Vista and Server 2008, __declspec(thread) works in DLLs only when those DLLs are bound to the executable, and will not work for those loaded with LoadLibrary() (a protection fault or data corruption may occur).[10]

Common Lisp and other dialects

[edit]

Common Lisp provides a feature called dynamically scoped variables.

Dynamic variables have a binding which is private to the invocation of a function and all of the children called by that function.

This abstraction naturally maps to thread-specific storage, and Lisp implementations that provide threads do this. Common Lisp has numerous standard dynamic variables, and so threads cannot be sensibly added to an implementation of the language without these variables having thread-local semantics in dynamic binding.

For instance the standard variable *print-base* determines the default radix in which integers are printed. If this variable is overridden, then until the override ends code will print integers in an alternate radix:

;;; function foo and its children will print
;; in hexadecimal:
(let ((*print-base* 16)) (foo))

If functions can execute concurrently on different threads, this binding has to be properly thread-local, otherwise each thread will fight over who controls a global printing radix.

D

[edit]

In D version 2, all static and global variables are thread-local by default and are declared with syntax similar to "normal" global and static variables in other languages. Global variables must be explicitly requested using the shared keyword:

int threadLocal;  // This is a thread-local variable.
shared int global;  // This is a global variable shared with all threads.

The shared keyword works both as the storage class, and as a type qualifier – shared variables are subject to some restrictions which statically enforce data integrity.[13] To declare a "classic" global variable without these restrictions, the unsafe __gshared keyword must be used:[14]

__gshared int global;  // This is a plain old global variable.

Java

[edit]

In Java, thread-local variables are implemented by the ThreadLocal class object.[15] ThreadLocal holds variable of type T,[15] which is accessible via get/set methods. For example, ThreadLocal variable holding Integer value looks like this:

private static final ThreadLocal<Integer> myThreadLocalInteger = new ThreadLocal<Integer>();

At least for Oracle/OpenJDK, this does not use native thread-local storage in spite of OS threads being used for other aspects of Java threading. Instead, each Thread object stores a (non-thread-safe) map of ThreadLocal objects to their values (as opposed to each ThreadLocal having a map of Thread objects to values and incurring a performance overhead).[16]

.NET languages: C# and others

[edit]

In .NET Framework languages such as C#, static fields can be marked with the ThreadStatic attribute:[17]: 898 

class FooBar
{
    [ThreadStatic]
    private static int _foo;
}

In .NET Framework 4.0 the System.Threading.ThreadLocal<T> class is available for allocating and lazily loading thread-local variables.[17]: 899 

class FooBar
{
    private static System.Threading.ThreadLocal<int> _foo;
}

Also an API is available for dynamically allocating thread-local variables.[17]: 899–890 

Object Pascal

[edit]

In Object Pascal (Delphi) or Free Pascal the threadvar reserved keyword can be used instead of 'var' to declare variables using the thread-local storage.

var
   mydata_process: integer;
threadvar
   mydata_threadlocal: integer;

Objective-C

[edit]

In Cocoa, GNUstep, and OpenStep, each NSThread object has a thread-local dictionary that can be accessed through the thread's threadDictionary method.

NSMutableDictionary *dict = [[NSThread currentThread] threadDictionary];
dict[@"A key"] = @"Some data";

Perl

[edit]

In Perl threads were added late in the evolution of the language, after a large body of extant code was already present on the Comprehensive Perl Archive Network (CPAN). Thus, threads in Perl by default take their own local storage for all variables, to minimise the impact of threads on extant non-thread-aware code. In Perl, a thread-shared variable can be created using an attribute:

use threads;
use threads::shared;

my $localvar;
my $sharedvar :shared;

PureBasic

[edit]

In PureBasic thread variables are declared with the keyword Threaded.

Threaded Var

Python

[edit]

In Python version 2.4 or later, local class in threading module can be used to create thread-local storage.

import threading
mydata = threading.local()
mydata.x = 1

Multiple instances of local class can be created to store different sets of variables.[18] Thus, it is not a singleton.

Ruby

[edit]

Ruby can create/access thread-local variables using []=/[] methods:

Thread.current[:user_id] = 1

Rust

[edit]

Thread-local variables can be created in Rust using the thread_local! macro provided by the Rust standard library:

use std::cell::RefCell;
use std::thread;

thread_local!(static FOO: RefCell<u32> = RefCell::new(1));

FOO.with(|f| {
    assert_eq!(*f.borrow(), 1);
    *f.borrow_mut() = 2;
});

// each thread starts out with the initial value of 1, even though this thread already changed its copy of the thread local value to 2
let t = thread::spawn(move || {
    FOO.with(|f| {
        assert_eq!(*f.borrow(), 1);
        *f.borrow_mut() = 3;
    });
});

// wait for the thread to complete and bail out on panic
t.join().unwrap();

// original thread retains the original value of 2 despite the child thread changing the value to 3 for that thread
FOO.with(|f| {
    assert_eq!(*f.borrow(), 2);
});

See also

[edit]
  • OpenMP — Another shared-memory multiprocessing facility which supports per-thread storage via "Data sharing attribute clauses" (see under §Clauses)

References

[edit]
  1. ^ Pietrek, Matt (May 2006). "Under the Hood". Microsoft Systems Journal. 11 (5). Archived from the original on 9 September 2010. Retrieved 6 April 2010.
  2. ^ "Concurrency support library - cppreference.com". en.cppreference.com.
  3. ^ Section 3.7.2 in C++11 standard
  4. ^ "C-Compiler Information Specific to Sun's Implementation". C User's Guide Sun Studio 8. 2004. 2.3 Thread Local Storage Specifier.
  5. ^ "XL C/C++ compilers". August 2010. Thread-local storage (TLS). Archived from the original on 11 April 2011.
  6. ^ "Thread-Local Storage". GCC 3.3.1 Manual. 2003.
  7. ^ "LLVM 2.0 Release Notes". 23 May 2007. llvm-gcc Improvements.
  8. ^ "Clang Language Extensions - Clang 3.8 documentation". Introduction. This document describes the language extensions provided by Clang. In addition to the language extensions listed here, Clang aims to support a broad range of GCC extensions. Please see the GCC manual for more information on these extensions.
  9. ^ "Intel® C++ Compiler 8.1 for Linux Release Notes For Intel IA-32 and Itanium® Processors" (PDF). 2004. Thread-local Storage. Archived from the original (PDF) on 19 January 2015.
  10. ^ a b Visual Studio 2003: "Thread Local Storage (TLS)". Microsoft Docs. 5 June 2017.
  11. ^ Intel C++ Compiler 10.0 (windows): Thread-local storage
  12. ^ "Attributes in Clang - Clang 3.8 documentation". thread.
  13. ^ Alexandrescu, Andrei (6 July 2010). "Chapter 13 - Concurrency". The D Programming Language. InformIT. p. 3. Retrieved 3 January 2014.
  14. ^ Bright, Walter (12 May 2009). "Migrating to Shared". dlang.org. Retrieved 3 January 2014.
  15. ^ a b Bloch 2018, p. 151-155, §Item 33: Consider typesafe heterogeneous containers.
  16. ^ "How is Java's ThreadLocal implemented under the hood?". Stack Overflow. Stack Exchange. Retrieved 27 December 2015.
  17. ^ a b c Albahari 2022.
  18. ^ "cpython/Lib/_threading_local.py at 3.12 · python/cpython". GitHub. Retrieved 25 October 2023.

Bibliography

[edit]
  • Albahari, Joseph (2022). C# 10 in a Nutshell (First ed.). O'Reilly. ISBN 978-1-098-12195-2.
  • Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991.


[edit]

Source: Wikipedia. Article content is retrieved live through the MediaWiki API.

No preview image
Wikipedia

Thread-local storage

In computer programming, thread-local storage (TLS) is a memory management method that uses static or global memory local to a thread. The concept allows storage of data that appears to be global in a system with separate threads. Many systems impose restrictions on the size of the thread-local memory block, in fact often rather tight limits. On the other hand, if a system can provide at least a memory address (pointer) sized variable thread-local, then this allows the use of arbitrarily sized memory blocks in a thread-local manner, by allocating such a memory block dynamically and storing the memory address of that block in the thread-local variable. On RISC machines, the calling convention often reserves a thread pointer register for this use.

MORE →
No preview image
Wikipedia

Portable Executable

Portable Executable (PE) is a file format for native executable code on 32-bit and 64-bit Windows operating systems, as well as in UEFI environments. It is used for native executables (.exe, .com), dynamic link libraries (.dll, .ocx), system drivers (.sys, .drv) and many other types of files. The PE format supports storing the data required to load and start an operating system process – including references to dynamic link libraries, tables for importing and exporting application programming interface (API) functions, resource management data and thread-local storage (TLS) information. According to the Unified Extensible Firmware Interface (UEFI) specification, the PE format is also the accepted standard for executables in EFI environments. On Windows NT systems, it currently supports a range of instruction sets, including IA-32, x86-64 (AMD64/Intel 64), IA-64, ARM and ARM64. Before the advent of Windows 2000, Windows NT (and by extension the PE format) also supported MIPS, Alpha, and PowerPC architectures. Moreover, thanks to its use in Windows CE, PE has maintained compatibility with several MIPS, ARM (including Thumb), and SuperH variants. Functionally, the PE format is similar to other platform-specific executable formats, such as the ELF format used in Linux and most Unix-like systems, and the Mach-O format found in macOS and iOS.

MORE →
No preview image
Wikipedia

.bss

In computer programming, the block starting symbol (abbreviated to .bss or bss) is the portion of an object file, executable, or assembly language code that contains statically allocated variables that are declared but have not been assigned a value yet. It is often referred to as the "bss section" or "bss segment". Typically only the length of the bss section, but no data, is stored in the object file. The program loader allocates memory for the bss section when it loads the program. By placing variables with no value in the .bss section, instead of the .data or .rodata section which require initial value data, the size of the object file is reduced. On some platforms, some or all of the bss section is initialized to zeroes. Unix-like systems and Windows initialize the bss section to zero, which can thus be used for C and C++ statically allocated variables that are initialized to all zero bits. Operating systems may use a technique called zero-fill-on-demand to efficiently implement the bss segment. In embedded software, the bss segment is mapped into memory that is initialized to zero by the C run-time system before main() is entered. Some C run-time systems may allow part of the bss segment not to be initialized; C variables must explicitly be placed into that portion of the bss segment. On some computer architectures, the application binary interface also supports an sbss segment for "small data". Typically, these data items can be accessed using shorter instructions that may only be able to access a certain range of addresses. Architectures supporting thread-local storage might use a tbss section for uninitialized, static data marked as thread-local.

MORE →
No preview image
Wikipedia

Local storage

Local storage may refer to: Data storage that is directly attached to a compute device A network-attached storage device accessed via a local network, rather than a wide area network Local storage, a JavaScript web storage facility allowing websites to store data on a user's device Local shared object (or Flash cookie), Adobe Flash data stored on a user's computer Scratchpad memory, computer memory closely integrated with a CPU or other component

MORE →
TOPIC OF THE DAY

Greenwood / Black Wall Street

Before the 1921 destruction of Tulsa’s Greenwood District, Black residents had created a remarkable center of business and community life. The district included stores, professional offices, entertainment venues and homes owned by Black citizens. Understanding Greenwood means learning what was built—not only what was burned.

MORE →
TRIVIA QUESTION OF THE DAY

Who became the first Black woman to travel into space?

Mae Jemison, aboard Space Shuttle Endeavour in 1992.