Deleting pointer sometimes results in heap corruption

前端 未结 7 591
深忆病人
深忆病人 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:23

    Use smart pointers or other RAII to handle your memory.


    If you have access to boost or tr1 lib you can do something like this.

    class ThreadPool
    {
        typedef pair > Job;
        list< Job > jobList;
        HANDLE mutex;
    
    public:
        void addJob(int jobid, const function& job) {
            jobList.push_back( make_pair(jobid, job) );
        }
    
        Job getNextJob() {    
    
            struct MutexLocker {
                HANDLE& mutex;
                MutexLocker(HANDLE& mutex) : mutex(mutex){ 
                    WaitForSingleObject(mutex, INFINITE); 
                }
                ~MutexLocker() { 
                    ReleaseMutex(mutex); 
                }
            };
    
            Job job = make_pair(-1, function());
            const MutexLocker locker(this->mutex);
            if (!this->jobList.empty()) {
                job = this->jobList.front();
                this->jobList.pop();
            }
            return job;
        }
    };
    
    
    void workWithDouble( double value );
    void workWithInt( int value );
    void workWithValues( int, double);
    
    void test() {
        ThreadPool pool;
        //...
        pool.addJob( 0, bind(&workWithDouble, 0.1));
        pool.addJob( 1, bind(&workWithInt, 1));
        pool.addJob( 2, bind(&workWithValues, 1, 0.1));
    }
    

提交回复
热议问题