|
16 | 16 | #include <stdexcept> |
17 | 17 | #include <string> |
18 | 18 | #include <cassert> |
| 19 | +#include <thread> |
| 20 | +#include <chrono> |
19 | 21 |
|
20 | 22 | #if defined(_MSC_VER) |
21 | 23 | #ifndef NOMINMAX |
@@ -364,9 +366,10 @@ class SlickQueue { |
364 | 366 | #ifndef UNICODE |
365 | 367 | std::string shmName = shm_name; |
366 | 368 | #else |
367 | | - int size_needed = MultiByteToWideChar(CP_UTF8, 0, shm_name, static_cast<int>(strlen(shm_name)), NULL, 0); |
| 369 | + int shm_name_sz = static_cast<int>(strlen(shm_name)); |
| 370 | + int size_needed = MultiByteToWideChar(CP_UTF8, 0, shm_name, shm_name_sz, NULL, 0); |
368 | 371 | std::wstring shmName(size_needed, 0); |
369 | | - MultiByteToWideChar(CP_UTF8, 0, shm_name, strlen(shm_name), &shmName[0], size_needed); |
| 372 | + MultiByteToWideChar(CP_UTF8, 0, shm_name, shm_name_sz, &shmName[0], size_needed); |
370 | 373 | #endif |
371 | 374 |
|
372 | 375 | if (open_only) { |
@@ -425,6 +428,11 @@ class SlickQueue { |
425 | 428 | if (err != ERROR_ALREADY_EXISTS) { |
426 | 429 | own_ = true; |
427 | 430 | } else { |
| 431 | + // when multiple process trying to create the same shared memory segment, |
| 432 | + // there is a chance that the segment is created but not yet initialized. |
| 433 | + // so we need to wait until the segment is initialized. |
| 434 | + std::this_thread::sleep_for(std::chrono::milliseconds(1)); |
| 435 | + |
428 | 436 | // Shared memory already exists, need to read and validate size |
429 | 437 | auto lpvMem = MapViewOfFile(hMapFile_, FILE_MAP_ALL_ACCESS, 0, 0, HEADER_SIZE); |
430 | 438 | if (!lpvMem) { |
@@ -481,6 +489,11 @@ class SlickQueue { |
481 | 489 | } |
482 | 490 | own_ = false; |
483 | 491 |
|
| 492 | + // when multiple process trying to create the same shared memory segment, |
| 493 | + // there is a chance that the segment is created but not yet initialized. |
| 494 | + // so we need to wait until the segment is initialized. |
| 495 | + std::this_thread::sleep_for(std::chrono::milliseconds(1)); |
| 496 | + |
484 | 497 | // Read size from shared memory and verify it matches |
485 | 498 | void* temp_map = mmap(nullptr, HEADER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd_, 0); |
486 | 499 | if (temp_map == MAP_FAILED) { |
|
0 commit comments