Deleting pointer sometimes results in heap corruption

前端 未结 7 606
深忆病人
深忆病人 2021-01-07 03:34

I have a multithreaded application that runs using a custom thread pool class. The threads all execute the same function, with different parameters.

These parameters

7条回答
  •  一生所求
    2021-01-07 04:09

    Thanks for extra code. Now we can see a problem -

    in getNextJob

    if (!this->jobs.empty())
    {
        job = &(this->jobs.front());
        this->jobs.pop();
    

    After the "pop", the memory pointed to by 'job' is undefined. Don't use a reference, copy the actual data!

    Try something like this (it's still generic, because JobData is generic):

    jobData ThreadPool::getNextJob()    // get the data of the next job
    {
      jobData job;
    
      WaitForSingleObject(this->mutex, INFINITE);
    
      if (!this->jobs.empty())
      {
        job = (this->jobs.front());
        this->jobs.pop();
      }
    
      // we're done with the exclusive part !
      ReleaseMutex(this->mutex);
    
      return job;
    

    }

    Also, while you're adding jobs to the queue you must ALSO lock the mutex, to prevent list corruption. AFAIK std::lists are NOT inherently thread-safe...?

提交回复
热议问题