From 59a7528fd6b0e80a648317433c14ba430587274c Mon Sep 17 00:00:00 2001 From: Thad House Date: Sun, 19 Dec 2021 13:39:23 -0800 Subject: [PATCH] [cscore] Fix crash when usbcamera is deleted before message pump thread fully starts (#3804) shared_from_this will assert if the shared pointer is in the middle of being destructed. Because we access shared_from_this in the message pump, this can easily occur. The solution is to grab the weak pointer, manually attempt to lock it, and only continue if that succeeds. The message pump is already synchronized to the usb camera being destructed, so this is a fine behavior. --- cscore/src/main/native/windows/UsbCameraImpl.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cscore/src/main/native/windows/UsbCameraImpl.cpp b/cscore/src/main/native/windows/UsbCameraImpl.cpp index 1a416726e8..efabf15f1c 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.cpp +++ b/cscore/src/main/native/windows/UsbCameraImpl.cpp @@ -485,9 +485,16 @@ bool UsbCameraImpl::DeviceConnect() { const wchar_t* path = m_widePath.c_str(); m_mediaSource = CreateVideoCaptureDevice(path); - if (!m_mediaSource) + if (!m_mediaSource) { return false; - m_imageCallback = CreateSourceReaderCB(shared_from_this(), m_mode); + } + auto weakThis = weak_from_this(); + auto sharedThis = weakThis.lock(); + if (sharedThis) { + m_imageCallback = CreateSourceReaderCB(sharedThis, m_mode); + } else { + return false; + } m_sourceReader = CreateSourceReader(m_mediaSource.Get(), m_imageCallback.Get());