Skip to content

Commit 1f01603

Browse files
committed
fix: resolve C++ mutex reinterpret_cast compilation errors
Replace problematic conditional mutex with WASI-compatible unique_lock pattern: - Remove invalid reinterpret_cast<std::mutex*>(nullptr) usage - Use std::unique_lock with std::defer_lock for conditional locking - Maintains thread safety when enabled while avoiding undefined behavior - Fixes compilation errors in memory_pool.cpp for data_structures_component
1 parent ca38972 commit 1f01603

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

examples/cpp_component/data_structures/src/memory_pool.cpp

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,11 @@ void* MemoryPool::allocate(size_t size) {
5858
return nullptr; // Graceful failure instead of crash
5959
}
6060

61-
std::lock_guard<std::mutex> lock(config_.enable_thread_safety ? mutex_ :
62-
*reinterpret_cast<std::mutex*>(nullptr));
61+
// WASI-compatible: Use proper conditional mutex locking
62+
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
63+
if (config_.enable_thread_safety) {
64+
lock.lock();
65+
}
6366

6467
size = align_size(size);
6568

@@ -118,8 +121,11 @@ void* MemoryPool::allocate_aligned(size_t size, size_t alignment) {
118121
void MemoryPool::deallocate(void* ptr) {
119122
if (!ptr) return;
120123

121-
std::lock_guard<std::mutex> lock(config_.enable_thread_safety ? mutex_ :
122-
*reinterpret_cast<std::mutex*>(nullptr));
124+
// WASI-compatible: Use proper conditional mutex locking
125+
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
126+
if (config_.enable_thread_safety) {
127+
lock.lock();
128+
}
123129

124130
if (!is_valid_pointer(ptr)) {
125131
if (config_.enable_debug) {
@@ -313,8 +319,11 @@ bool MemoryPool::expand_pool(size_t additional_size) {
313319
}
314320

315321
MemoryStats MemoryPool::get_stats() const {
316-
std::lock_guard<std::mutex> lock(config_.enable_thread_safety ? mutex_ :
317-
*reinterpret_cast<std::mutex*>(nullptr));
322+
// WASI-compatible: Use proper conditional mutex locking
323+
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
324+
if (config_.enable_thread_safety) {
325+
lock.lock();
326+
}
318327

319328
MemoryStats stats = {};
320329
stats.current_usage = static_cast<uint32_t>(used_size_);
@@ -391,8 +400,11 @@ void MemoryPool::check_corruption(const BlockHeader* block) const {
391400
}
392401

393402
bool MemoryPool::validate_heap() const {
394-
std::lock_guard<std::mutex> lock(config_.enable_thread_safety ? mutex_ :
395-
*reinterpret_cast<std::mutex*>(nullptr));
403+
// WASI-compatible: Use proper conditional mutex locking
404+
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
405+
if (config_.enable_thread_safety) {
406+
lock.lock();
407+
}
396408

397409
// Validate all blocks in free list
398410
BlockHeader* current = free_list_head_;

0 commit comments

Comments
 (0)