11
11
namespace facebook ::torchcodec {
12
12
13
13
namespace {
14
+ using DeviceInterfaceMap = std::map<torch::DeviceType, CreateDeviceInterfaceFn>;
14
15
std::mutex g_interface_mutex;
15
- std::map<torch::DeviceType, CreateDeviceInterfaceFn > g_interface_map;
16
+ std::unique_ptr<DeviceInterfaceMap > g_interface_map;
16
17
17
18
std::string getDeviceType (const std::string& device) {
18
19
size_t pos = device.find (' :' );
@@ -28,11 +29,18 @@ bool registerDeviceInterface(
28
29
torch::DeviceType deviceType,
29
30
CreateDeviceInterfaceFn createInterface) {
30
31
std::scoped_lock lock (g_interface_mutex);
32
+ if (!g_interface_map) {
33
+ // We delay this initialization until runtime to avoid the Static
34
+ // Initialization Order Fiasco:
35
+ //
36
+ // https://en.cppreference.com/w/cpp/language/siof
37
+ g_interface_map = std::make_unique<DeviceInterfaceMap>();
38
+ }
31
39
TORCH_CHECK (
32
- g_interface_map. find (deviceType) == g_interface_map. end (),
40
+ g_interface_map-> find (deviceType) == g_interface_map-> end (),
33
41
" Device interface already registered for " ,
34
42
deviceType);
35
- g_interface_map. insert ({deviceType, createInterface});
43
+ g_interface_map-> insert ({deviceType, createInterface});
36
44
return true ;
37
45
}
38
46
@@ -45,14 +53,16 @@ torch::Device createTorchDevice(const std::string device) {
45
53
std::scoped_lock lock (g_interface_mutex);
46
54
std::string deviceType = getDeviceType (device);
47
55
auto deviceInterface = std::find_if (
48
- g_interface_map. begin (),
49
- g_interface_map. end (),
56
+ g_interface_map-> begin (),
57
+ g_interface_map-> end (),
50
58
[&](const std::pair<torch::DeviceType, CreateDeviceInterfaceFn>& arg) {
51
59
return device.rfind (
52
60
torch::DeviceTypeName (arg.first , /* lcase*/ true ), 0 ) == 0 ;
53
61
});
54
62
TORCH_CHECK (
55
- deviceInterface != g_interface_map.end (), " Unsupported device: " , device);
63
+ deviceInterface != g_interface_map->end (),
64
+ " Unsupported device: " ,
65
+ device);
56
66
57
67
return torch::Device (device);
58
68
}
@@ -67,11 +77,12 @@ std::unique_ptr<DeviceInterface> createDeviceInterface(
67
77
68
78
std::scoped_lock lock (g_interface_mutex);
69
79
TORCH_CHECK (
70
- g_interface_map. find (deviceType) != g_interface_map. end (),
80
+ g_interface_map-> find (deviceType) != g_interface_map-> end (),
71
81
" Unsupported device: " ,
72
82
device);
73
83
74
- return std::unique_ptr<DeviceInterface>(g_interface_map[deviceType](device));
84
+ return std::unique_ptr<DeviceInterface>(
85
+ (*g_interface_map)[deviceType](device));
75
86
}
76
87
77
88
} // namespace facebook::torchcodec
0 commit comments