0

I want to make asynchronous writes in stream.
In code below functions streaming and push_stream runs in parallel threads by using CreateThread winapi function. And std::lock_guard<std::mutex> should lock the queue from random access. But I have some issue with this instance of code. When queue pops items, I get Microsoft Visual C++ Runtime Library error __acrt_first_block == header

std::ofstream somestream;
std::queue<std::string> queue;
std::mutex mutexQueue;

void streaming() {
  while (true) {
    if (!queue.empty()) {
      std::lock_guard<std::mutex> lock(mutexQueue);

      while (!queue.empty()) {
          somestream << queue.front();
          queue.pop();
      }
    }
  }
}

void push_stream(std::string str) {
  std::lock_guard<std::mutex> lock(mutexQueue);
  queue.push(str);
}

How to make this kind of asynchronous writes? I've tried concurrent_queue but it hasn't a thread-safe item removing.

UPD

Problem was in .dll and .exe static linked with RT. Functions implemented in .exe, push_stream called from .dll. Which cause the Debug Assertion Failed! Expression: _pFirstBlock == pHead

Now issue is fixed.

ComradeAndrew
  • 148
  • 3
  • 11
  • `std::queue` looks like a bad container choice. –  Jun 18 '15 at 21:00
  • How about boost::asio? io_service::run + io_service::work + callback functor would work perfectly. No explicit locking and less code. – UldisK Jun 18 '15 at 21:07
  • The mutex should make this thread-safe, perhaps your problem is elsewhere? – Jonathan Potter Jun 18 '15 at 21:10
  • @DieterLücking you are right. It is because std::string in container. Is it possible to contain std::string, even without [] access, by this way and don't use the boost? – ComradeAndrew Jun 18 '15 at 21:10
  • The access to `empty()` outside the mutex-protected region is unsafe. – Alan Stokes Jun 18 '15 at 21:52
  • @AlanStokes: Unsafe in the sense that it gives an unreliable result, but it won't cause a crash. – Jonathan Potter Jun 18 '15 at 23:46
  • **Crash** gives `std::string` in `std::queue`. Any idea how to avoid it? – ComradeAndrew Jun 19 '15 at 08:13
  • @JonathanPotter Unsafe in the sense that you get undefined behavior. So even if it doesn't crash now, it might very well start crashing in a future version of the implementation. Just don't use double-checked locking this way. It accomplishes nothing but causing serious maintenance headaches. – ComicSansMS Jun 23 '15 at 07:28

0 Answers0