{"record":{"id":"952f63d8e4fe5591","repo":"tokio-rs/tokio","slug":"cannot-create-localset-during-thread-shutdown","errorCode":null,"errorMessage":"cannot create LocalSet during thread shutdown","messagePattern":"cannot create LocalSet during thread shutdown","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tokio/src/task/local.rs","lineNumber":504,"sourceCode":"                 wake_on_schedule,\n             }| {\n                ctx.set(self.ctx.take());\n                wake_on_schedule.set(self.wake_on_schedule);\n            },\n        );\n    }\n}\n\nimpl fmt::Debug for LocalEnterGuard {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        f.debug_struct(\"LocalEnterGuard\").finish()\n    }\n}\n\nimpl LocalSet {\n    /// Returns a new local task set.\n    pub fn new() -> LocalSet {\n        let owner = context::thread_id().expect(\"cannot create LocalSet during thread shutdown\");\n\n        LocalSet {\n            tick: Cell::new(0),\n            context: Rc::new(Context {\n                shared: Arc::new(Shared {\n                    local_state: LocalState {\n                        owner,\n                        owned: LocalOwnedTasks::new(),\n                        local_queue: UnsafeCell::new(VecDeque::with_capacity(INITIAL_CAPACITY)),\n                    },\n                    queue: Mutex::new(Some(VecDeque::with_capacity(INITIAL_CAPACITY))),\n                    waker: AtomicWaker::new(),\n                    #[cfg(tokio_unstable)]\n                    unhandled_panic: crate::runtime::UnhandledPanic::Ignore,\n                }),\n                unhandled_panic: Cell::new(false),\n            }),\n            _not_send: PhantomData,","sourceCodeStart":486,"sourceCodeEnd":522,"githubUrl":"https://github.com/tokio-rs/tokio/blob/7d0d729d8f03a0033d6752730d0fb5928962560e/tokio/src/task/local.rs#L486-L522","documentation":"LocalSet::new() calls context::thread_id().expect('cannot create LocalSet during thread shutdown'). thread_id() returns None when the current thread is in the middle of TLS/thread destruction (pthread exit / thread shutdown phase), so tokio refuses to construct a LocalSet there.","triggerScenarios":"Constructing LocalSet::new() from a Drop impl, destructor, or atexit/thread-local destructor that runs during thread teardown; spawning a LocalSet from cleanup code on a dying thread.","commonSituations":"Lazy statics / thread-locals creating a LocalSet on first access during teardown; background thread exiting while another Drop tries to make a LocalSet; libraries that lazily initialize async runtimes in destructors.","solutions":["Create the LocalSet eagerly when the thread starts, not in Drop/destructors.","Avoid instantiating LocalSet inside thread-local destructors or atexit handlers.","Guard cleanup code that may run on shutdown from creating new runtimes/LocalSets.","Refactor so the LocalSet lifetime is owned by normal scope, not tied to teardown."],"exampleFix":"// before\nthread_local! {\n    static LS: LocalSet = LocalSet::new(); // panics if first touch is during shutdown\n}\n// after\nlet ls = LocalSet::new(); // created in normal scope\nls.block_on(async { /* ... */ });","handlingStrategy":"validation","validationCode":"// Construct the LocalSet in normal scope, never in Drop/destructors.\nlet ls = tokio::task::LocalSet::new();","typeGuard":null,"tryCatchPattern":"// Avoid creating LocalSet during shutdown; catch_unwind only as last resort:\nstd::panic::catch_unwind(|| tokio::task::LocalSet::new())\n    .map_err(|_| io::Error::new(io::ErrorKind::Other, \"cannot create LocalSet during shutdown\"))?","preventionTips":["Create LocalSet eagerly at thread start, not lazily.","Never instantiate LocalSet inside thread-local destructors.","Keep runtime/LocalSet lifetime outside teardown paths."],"tags":["localset","task","thread-shutdown","panic","tls"],"backgroundTag":null,"analyzedSha":"7d0d729d8f03a0033d6752730d0fb5928962560e","analyzedAt":"2026-08-11T17:46:45.378Z","contentChangedAt":"2026-08-11T17:46:45.378Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}