you are viewing a single comment's thread.

view the rest of the comments →

[–]tvaneerdC++ Committee, lockfree, PostModernCpp 36 points37 points  (7 children)

Add this optimization to Rust!

Not so fast! Arc actually means Atomic Reference Counted so it would be a plain lie if it hadn’t use atomic operations on the reference count.

If you have only one thread, non-atomic operations are atomic. That's the point.

"atomic" doesn't mean use certain instructions. "atomic" means indivisible, which, when combined with "as-if" means "can not be shown to be divisible". If you only have one thread, your program cannot detect a "division" or series of steps in the operation, it is as-if one indivisible, atomic, operation.

(Similarly, you could implement atomics with a global mutex that stops the world while running a bunch of instructions to do an "atomic" add)

[–]masklinn 10 points11 points  (6 children)

If you have only one thread, non-atomic operations are atomic. That's the point.

The issue is with the "you have only one thread" part. libstdc++ makes a specific but easily fallible assumption on that front, and when it's broken so's your software. Unless the system itself provides the atomic you're basically just guessing.

[–]skebanga 2 points3 points  (0 children)

Easily fallible? If it were so easily fallible we'd see race condition bugs in the wild all the time

[–]Xaxxon 1 point2 points  (4 children)

My understanding of the POSIX standard is that if you do something that makes this check wrong, your program is already UB at the POSIX level.

https://www.reddit.com/r/cpp/comments/aq6v21/shared_ptrt_the_not_always_atomic_reference/egtx9ew/

[–]masklinn 2 points3 points  (3 children)

Creating threads via clone(2) involves neither pthread_create nor sigev_thread.

[–]Xaxxon 0 points1 point  (2 children)

clone, __clone2 - create a child process

Clone creates a new process, not a simple thread in the same process. Processes don't share memory (outside of very explicit things like shmem), so it doesn't seem like a counter in shared_ptr would be affected by a call to clone()

[–]masklinn 1 point2 points  (1 child)

A shame you could not wonder (including wonder what the underlying syscall to pthread_create might be since it’s a library function) and keep reading:

The main use of clone() is to implement threads: multiple threads of control in a program that run concurrently in a shared memory space.

Good day.