PTHREAD..._DESTROY(3POSIX)
okay bestie, welcome to PTHREAD..._DESTROY(3POSIX) from the POSIX Programmer's Manual π
this is part 1 of a two-parter, so buckle up π
πΈ PROLOG πΈ
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
translation: this is the POSIX spec version, not necessarily your Linux box's version, so double-check before you come for me π
β¨ NAME β¨
pthread_mutexattr_destroy, pthread_mutexattr_init β destroy and initialize the mutex attributes object
yes, "destroy and initialize" in one breath. it's giving duality. it's giving main character energy. π
π¦ SYNOPSIS π¦
#include <pthread.h>
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
π DESCRIPTION π
pthread_mutexattr_destroy() shall destroy a mutex attributes object; the object becomes, in effect, uninitialized. An implementation may cause pthread_mutexattr_destroy() to set the object referenced by attr to an invalid value.
so basically it ghosted the object. the object is now uninit, and it might even be an invalid value. either way, do not text it back. π
A destroyed attr attributes object can be reinitialized using pthread_mutexattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined.
β οΈ undefined behavior alert β οΈ β "the results of otherwise referencing the object after it has been destroyed are undefined". that is spec-speak for "anything can happen and none of it is my fault". don't touch a destroyed attr. i'm serious. π
The pthread_mutexattr_init() function shall initialize a mutex attributes object attr with the default value for all of the attributes defined by the implementation.
Results are undefined if pthread_mutexattr_init() is called specifying an already initialized attr attributes object.
double-init = undefined behavior. do not init twice. that's not a glow-up, that's a bug. π
After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes.
this one is lowkey the sweetest part: once your attrs have made some mutexes, messing with the attrs later (even destroying them) doesn't reach back and mess with the mutexes you already made. they're grown. they're independent. periodt. β¨
The behavior is undefined if the value specified by the attr argument to pthread_mutexattr_destroy() does not refer to an initialized mutex attributes object.
π₯ RETURN VALUE π₯
Upon successful completion, pthread_mutexattr_destroy() and pthread_mutexattr_init() shall return zero; otherwise, an error number shall be returned to indicate the error.
0 = slay. anything else = it's giving error number, go read the error. π
π ERRORS π
The pthread_mutexattr_init() function shall fail if:
ENOMEMβ Insufficient memory exists to initialize the mutex attributes object.
that's the only one, bestie. not a long list. we love a short list. π
These functions shall not return an error code of [EINTR].
The following sections are informative.
^ meaning everything from here on is informative-only, i.e. the vibe section. still canon, still useful, just not normative-normative. iykyk π§
π EXAMPLES π
None.
not me expecting examples and getting "None." π okay. moving on.
π APPLICATION USAGE π
None.
again with the "None." π we are being fed crumbs and honestly? respecting it.
π RATIONALE π
If an implementation detects that the value specified by the attr argument to pthread_mutexattr_destroy() does not refer to an initialized mutex attributes object, it is recommended that the function should fail and report an [EINVAL] error.
note the word "recommended" β that's a should, not a shall. so don't be shocked if your implementation just shrugs. π«Ά
See pthread_attr_destroy() for a general explanation of attributes. Attributes objects allow implementations to experiment with useful extensions and permit extension of this volume of POSIX.1β2017 without changing the existing functions. Thus, they provide for future extensibility of this volume of POSIX.1β2017 and reduce the temptation to standardize prematurely on semantics that are not yet widely implemented or understood.
so the whole point of attrs objects is: let implementations cook π³ without breaking the existing function signatures. it's a future-proofing situation. iconic, honestly.
Examples of possible additional mutex attributes that have been discussed are spin_only, limited_spin, no_spin, recursive, and metered. (To explain what the latter attributes might mean: recursive mutexes would allow for multiple re-locking by the current owner; metered mutexes would transparently keep records of queue length, wait time, and so on.) Since there is not yet wide agreement on the usefulness of these resulting from shared implementation and usage experience, they are not yet specified in this volume of POSIX.1β2017. Mutex attributes objects, however, make it possible to test out these concepts for possible standardization at a later time.
so spin_only, limited_spin, no_spin, recursive, and metered are the "we talked about it at brunch but nobody agreed" list. not specified yet. don't go using them like they're real. π«
π Mutex Attributes and Performance π
Care has been taken to ensure that the default values of the mutex attributes have been defined such that mutexes initialized with the defaults have simple enough semantics so that the locking and unlocking can be done with the equivalent of a test-and-set instruction (plus possibly a few other basic instructions).
default attrs = fast path. they deliberately kept the defaults simple enough that lock/unlock is basically a test-and-set plus maybe a couple other basic instructions. efficient queen. π
There is at least one implementation method that can be used to reduce the cost of testing at lock-time if a mutex has non-default attributes. One such method that an implementation can employ (and this can be made fully transparent to fully conforming POSIX applications) is to secretly pre-lock any mutexes that are initialized to non-default attributes. Any later attempt to lock such a mutex causes the implementation to branch to the "slow path" as if the mutex were unavailable; then, on the slow path, the implementation can do the "real work" to lock a non-default mutex. The underlying unlock operation is more complicated since the implementation never really wants to release the pre-lock on this kind of mutex. This illustrates that, depending on the hardware, there may be certain optimizations that can be used so that whatever mutex attributes are considered "most frequently used" can be processed most efficiently.
the tea β: an implementation can secretly pre-lock mutexes that were made with non-default attrs, so a later lock attempt just branches to the "slow path" like it was unavailable, and the "real work" happens over there. unlock gets messier because it never actually wants to release that pre-lock. fully transparent to conforming apps, though. and it means: whatever attrs get used "most frequently" can get the most efficient treatment, depending on the hardware. optimize your faves. π
π¦ Process Shared Memory and Synchronization π¦
The existence of memory mapping functions in this volume of POSIX.1β2017 leads to the possibility that an application may allocate the synchronization objects from this section in memory that is accessed by multiple processes (and therefore, by threads of multiple processes).
In order to permit such usage, while at the same time keeping the usual case (that is, usage within a single process) efficient, a process-shared option has been defined.
If an implementation supports the _POSIX_THREAD_PROCESS_SHARED option, then the process-shared attribute can be used to indicate that mutexes or condition variables may be accessed by threads of multiple processes.
The default setting of PTHREAD_PROCESS_PRIVATE has been chosen for the process-shared attribute so that the most efficient forms of these synchronization objects are created by default.
so: default = PTHREAD_PROCESS_PRIVATE because single-process is the common case and they wanted it fast. you only opt into sharing. no accidental sharing. we love a safe default. π«Ά
Synchronization variables that are initialized with the PTHREAD_PROCESS_PRIVATE process-shared attribute may only be operated on by threads in the process that initialized them. Synchronization variables that are initialized with the PTHREAD_PROCESS_SHARED process-shared attribute may be operated on by any thread in any process that has access to it. In particular, these processes may exist beyond the lifetime of the initializing process. For example, the following code implements a simple counting semaphore in a mapped file that may be used by many processes.
read this twice, bestie: PTHREAD_PROCESS_PRIVATE = only threads in the process that initialized it. PTHREAD_PROCESS_SHARED = any thread in any process that has access, and those processes can outlive the initializing process. it's giving generational. π
/* sem.h */
struct semaphore {
pthread_mutex_t lock;
pthread_cond_t nonzero;
unsigned count;
};
typedef struct semaphore semaphore_t;
semaphore_t *semaphore_create(char *semaphore_name);
semaphore_t *semaphore_open(char *semaphore_name);
void semaphore_post(semaphore_t *semap);
void semaphore_wait(semaphore_t *semap);
void semaphore_close(semaphore_t *semap);
/* sem.c */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include "sem.h"
semaphore_t *
semaphore_create(char *semaphore_name)
{
int fd;
semaphore_t *semap;
pthread_mutexattr_t psharedm;
pthread_condattr_t psharedc;
fd = open(semaphore_name, O_RDWR | O_CREAT | O_EXCL, 0666);
if (fd < 0)
return (NULL);
(void) ftruncate(fd, sizeof(semaphore_t));
(void) pthread_mutexattr_init(&psharedm);
(void) pthread_mutexattr_setpshared(&psharedm,
PTHREAD_PROCESS_SHARED);
(void) pthread_condattr_init(&psharedc);
(void) pthread_condattr_setpshared(&psharedc,
PTHREAD_PROCESS_SHARED);
semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t),
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
close (fd);
(void) pthread_mutex_init(&semap->lock, &psharedm);
(void) pthread_cond_init(&semap->nonzero, &psharedc);
semap->count = 0;
return (semap);
}
semaphore_t *
semaphore_open(char *semaphore_name)
{
int fd;
semaphore_t *semap;
fd = open(semaphore_name, O_RDWR, 0666);
if (fd < 0)
return (NULL);
semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t),
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
close (fd);
return (semap);
}
void
semaphore_post(semaphore_t *semap)
{
pthread_mutex_lock(&semap->lock);
if (semap->count == 0)
pthread_cond_signal(&semapx->nonzero);
semap->count++;
pthread_mutex_unlock(&semap->lock);
}
void
semaphore_wait(semaphore_t *semap)
{
pthread_mutex_lock(&semap->lock);
while (semap->count == 0)
pthread_cond_wait(&semap->nonzero, &semap->lock);
semap->count--;
pthread_mutex_unlock(&semap->lock);
}
void
semaphore_close(semaphore_t *semap)
{
munmap((void *) semap, sizeof(semaphore_t));
}
i am copy-pasting this exactly as the spec has it, semapx typo and all, because my job is to keep the facts, not to fix the source. π
The following code is for three separate processes that create, post, and wait on a semaphore in the file /tmp/semaphore. Once the file is created, the post and wait programs increment and decrement the counting semaphore (waiting and waking as required) even though they did not initialize the semaphore.
/* create.c */
#include "pthread.h"
#include "sem.h"
int
main()
{
semaphore_t *semap;
semap = semaphore_create("/tmp/semaphore");
if (semap == NULL)
exit(1);
semaphore_close(semap);
return (0);
}
/* post */
#include "pthread.h"
#include "sem.h"
int
main()
{
semaphore_t *semap;
semap = semaphore_open("/tmp/semaphore");
if (semap == NULL)
exit(1);
semaphore_post(semap);
semaphore_close(semap);
return (0);
}
/* wait */
#include "pthread.h"
#include "sem.h"
int
main()
{
semaphore_t *semap;
semap = semaphore_open("/tmp/semaphore");
if (semap == NULL)
exit(1);
semaphore_wait(semap);
semaphore_close(semap);
return (0);
}
three whole separate processes, one file, one semaphore, and only one of them actually created it. the other two just show up and start posting and waiting. that's the process-shared dream, bestie. π
β FUTURE DIRECTIONS β
None.
π«Ά SEE ALSO π«Ά
pthread_cond_destroy()pthread_create()pthread_mutex_destroy()
The Base Definitions volume of POSIX.1β2017, <pthread.h>
β¨ COPYRIGHT β¨
okay so bestie, legal bit incoming but it's important, don't skip it π«Ά
Big chunks of this text are reprinted and reproduced in electronic form straight from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, and the copyright on that is (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. iconic of them honestly π
and if this version ever beefs with the original IEEE and The Open Group Standard? the original is the referee document, no cap. this one's just the vibe, the original is the law. π
you can go get the original Standard online at http://www.opengroup.org/unix/online.html if you wanna read the source material yourself, periodt β¨
π about any typos / weird formatting π
any typographical or formatting errors that show up in this page? most likely got introduced during the conversion of the source files to man page format. it's giving "translation glitch", not "the standard said that" π so if you spot one, report it β here's where:
https://www.kernel.org/doc/man-pages/reporting_bugs.html
and that's the whole page, bestie!! you made it to the end π¦πΈ thanks for reading all the way through, I'm so proud of you fr fr π
this came from IEEE/The Open Group, dated 2017, and it's the PTHREAD..._DESTROY(3POSIX) page β go forth and destroy those threads responsibly, mwah π
β¨
π¦ where this page comes from
- debian bookworm: manpages-posix-dev 2017a-2 Β· Other
- debian trixie: manpages-posix-dev 2017a-2 Β· Other
- ubuntu jammy: manpages-posix-dev 2017a-2 Β· Other
- ubuntu noble: manpages-posix-dev 2017a-2 Β· Other
- ubuntu resolute: manpages-posix-dev 2017a-2build1 Β· Other
- ubuntu stonking: manpages-posix-dev 2017a-2.1 Β· Other
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms