Skip to content

ReentrantLock can be held by multiple threads at the same time #123458

Closed
@tmiasko

Description

@tmiasko

The code below verifies that the only one thread holds the ReentrantLock by recording the owner thread id inside. It should be true since the lock is never unlocked (note that the lock guard is leaked). In practice, in some executions the assertion fails:

#![feature(reentrant_lock)]
#![feature(thread_id_value)]

use std::cell::Cell;
use std::mem::ManuallyDrop;
use std::sync::ReentrantLock;
use std::thread;

fn main() {
    let lock = ReentrantLock::new(Cell::new(None));
    let run = || {
        let id = ManuallyDrop::new(lock.lock());
        match id.get() {
            None => id.set(Some(thread::current().id())),
            Some(id) => assert_eq!(id, thread::current().id()),
        }
    };
    thread::scope(|s| {
        s.spawn(run);
    });
    thread::scope(|s| {
        s.spawn(run);
    });
}
$ cargo run
thread '<unnamed>' panicked at src/main.rs:15:25:
assertion `left == right` failed
  left: ThreadId(2)
 right: ThreadId(3)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at src/main.rs:21:5:
a scoped thread panicked

Inspired by report from rust-lang/miri#3450, which also explains why this fails.

Ideally the assertion failure wouldn't be among possible executions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-atomicArea: Atomics, barriers, and sync primitivesA-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-bugCategory: This is a bug.T-libsRelevant to the library team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions