Skip to content

Commit 7b7b4d2

Browse files
committed
Make init/shutdown thread safe
1 parent 70763f4 commit 7b7b4d2

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

torchaudio/csrc/sox_effects.cpp

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,48 @@
11
#include <sox.h>
22
#include <torchaudio/csrc/sox_effects.h>
33

4-
using namespace torch::indexing;
5-
64
namespace torchaudio {
75
namespace sox_effects {
86

97
namespace {
108

119
enum SoxEffectsResourceState { NotInitialized, Initialized, ShutDown };
1210
SoxEffectsResourceState SOX_RESOURCE_STATE = NotInitialized;
11+
std::mutex SOX_RESOUCE_STATE_MUTEX;
1312

1413
} // namespace
1514

1615
void initialize_sox_effects() {
17-
if (SOX_RESOURCE_STATE == ShutDown) {
18-
throw std::runtime_error(
19-
"SoX Effects has been shut down. Cannot initialize again.");
20-
}
21-
if (SOX_RESOURCE_STATE == NotInitialized) {
22-
if (sox_init() != SOX_SUCCESS) {
23-
throw std::runtime_error("Failed to initialize sox effects.");
24-
};
25-
SOX_RESOURCE_STATE = Initialized;
16+
const std::lock_guard<std::mutex> lock(SOX_RESOUCE_STATE_MUTEX);
17+
18+
switch (SOX_RESOURCE_STATE) {
19+
case NotInitialized:
20+
if (sox_init() != SOX_SUCCESS) {
21+
throw std::runtime_error("Failed to initialize sox effects.");
22+
};
23+
SOX_RESOURCE_STATE = Initialized;
24+
case Initialized:
25+
break;
26+
case ShutDown:
27+
throw std::runtime_error(
28+
"SoX Effects has been shut down. Cannot initialize again.");
2629
}
2730
};
2831

2932
void shutdown_sox_effects() {
30-
if (SOX_RESOURCE_STATE == NotInitialized) {
31-
throw std::runtime_error(
32-
"SoX Effects is not initialized. Cannot shutdown.");
33-
}
34-
if (SOX_RESOURCE_STATE == Initialized) {
35-
if (sox_quit() != SOX_SUCCESS) {
36-
throw std::runtime_error("Failed to initialize sox effects.");
37-
};
38-
SOX_RESOURCE_STATE = ShutDown;
33+
const std::lock_guard<std::mutex> lock(SOX_RESOUCE_STATE_MUTEX);
34+
35+
switch (SOX_RESOURCE_STATE) {
36+
case NotInitialized:
37+
throw std::runtime_error(
38+
"SoX Effects is not initialized. Cannot shutdown.");
39+
case Initialized:
40+
if (sox_quit() != SOX_SUCCESS) {
41+
throw std::runtime_error("Failed to initialize sox effects.");
42+
};
43+
SOX_RESOURCE_STATE = ShutDown;
44+
case ShutDown:
45+
break;
3946
}
4047
}
4148

0 commit comments

Comments
 (0)