IntelRealSense / librealsense

Intel® RealSense™ SDK
https://www.intelrealsense.com/
Apache License 2.0
7.6k stars 4.83k forks source link

C++: Multithreaded Multi-Depthsensor Close causes Memory Access Violation #5250

Closed MojamojaK closed 4 years ago

MojamojaK commented 4 years ago
Required Info
Camera Model D415 (20 of them)
Firmware Version 5.11.15.0
Operating System & Version Win10
Platform PC
SDK Version 2.30.1
Language C++14
Segment 3D
USING NEW FORCE_RSUSB_BACKEND OPTION

Issue Description

I am currently using twenty D415 devices simultaneously for depth-image capturing.

Due to the time sensitivity of the application, all depth sensor methods are being executed in a multithreaded behavior. ex) (error handling omitted for better readability)

std::vector<rs2::sensor> sensors;
// emplace DEPTH sensors from rs2::device here
// open, start, get/keep frames and stop sensors here (multithreaded per device)

std::vector<std::thread> threads;
for (auto &&sensor: sensors) {
    threads.emplace_back(std::thread([&](){
        sensor.close();
    }));
}
for (auto &&thread: threads) {
    thread.join();
}

Memory Access Violation (write violation) crash occurs around 50% of the time during multithreaded sensor.close() across multiple device sensors. It happens when the used video profile is

profile option value
stream RS2_STREAM_DEPTH
format RS2_FORMAT_Z16
fps 6
resolution 1280x720
stream index 0

and does not happen when

profile option value
stream RS2_STREAM_INFRARED
format RS2_FORMAT_Y8
fps 6
resolution 1280x720
stream index 1

VS debug indicates that Unhandled exception at 0x00007FFF212847CF (realsense2.dll) in main.exe: 0xC0000005: Access violation writing location 0x0000000000000009. _sensor=identifier "_sensor" is undefined at rs_sensor.hpp

        void close() const
        {
            rs2_error* e = nullptr;
            rs2_close(_sensor.get(), &e); // crash occurs here
            error::handle(e);
        }

FYI There is no problem when a mutex is used, ex

std::mutex m;
for (auto &&sensor: sensors) {
    threads.emplace_back(std::thread([&](){
        std::lock_guard<std::mutex> _(m);
        sensor.close();
    }));
}

or executed in a sequential manner, ex

for (auto &&sensor: sensors) {
        sensor.close();
}
RealSenseCustomerSupport commented 4 years ago

Does the problem still persists?