Skip to content

ID3D11DeviceContext is Sync despite the docs saying otherwise #2239

@AlsoSylv

Description

@AlsoSylv

Summary

In Introduction to Multi-threading in Direct3D 11 it is explicitly stated that usage of a single context across threads requires some form of external synchronization, such as a mutex. However, ID3D11DeviceContext currently implements Sync.

This is not in line with the definition of Sync which states that types that can be sent across threads and cause data-races are !Sync.

Crate manifest

[package]
name = "sync_issue_example"

[target.'cfg(windows)'.dependencies.windows]
version = "0.62"
features = [
    "Win32_Graphics_Dxgi_Common",
    "Win32_Graphics_Direct3D",
    "Win32_Graphics_Direct3D11",
]

Crate code

use windows::Win32::{
    Foundation::HMODULE,
    Graphics::{
        Direct3D::{D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL_11_0},
        Direct3D11::{D3D11_CREATE_DEVICE_FLAG, D3D11_SDK_VERSION, D3D11CreateDevice},
    },
};

fn main() {
    let dxgi_factory: windows::Win32::Graphics::Dxgi::IDXGIFactory =
        unsafe { windows::Win32::Graphics::Dxgi::CreateDXGIFactory() }.unwrap();
    let dxgi_adapter = unsafe { dxgi_factory.EnumAdapters(0) }.unwrap();

    let desc = unsafe { dxgi_adapter.GetDesc() }.unwrap();
    println!("{:?}", windows::core::HSTRING::from_wide(&desc.Description));

    let mut device = None;
    let mut device_context = None;
    unsafe {
        D3D11CreateDevice(
            &dxgi_adapter,
            D3D_DRIVER_TYPE_UNKNOWN,
            HMODULE(std::ptr::null_mut()),
            D3D11_CREATE_DEVICE_FLAG(0),
            Some(&[D3D_FEATURE_LEVEL_11_0]),
            D3D11_SDK_VERSION,
            Some(&raw mut device),
            None,
            Some(&raw mut device_context),
        )
    }
    .unwrap();
    let device = device.unwrap();
    let _device_context = device_context.unwrap();

    let cloned = _device_context.clone();

    let handle  = std::thread::spawn(|| {
        // Context is now usable on two threads, which can cause deadlocks and errors.
        cloned
    });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions