c++ - Error with function in multithreaded environment -



c++ - Error with function in multithreaded environment -

what function iterate through array of bools , upon finding element set false, set true. function method memory manager singleton class returns pointer memory. i'm getting error iterator appears loop through , ends starting @ beginning, believe because multiple threads calling function.

void* cnetworkmemorymanager::getmemory() { waitforsingleobject(hmutexcounter, infinite); if(mcounter >= netconsts::knummemoryslots) { mcounter = 0; } unsigned int tempcounter = mcounter; unsigned int start = tempcounter; while(musedslots[tempcounter]) { tempcounter++; if(tempcounter >= netconsts::knummemoryslots) { tempcounter = 0; } //looped way around if(tempcounter == start) { assert(false); homecoming null; } } //return pointer free space , increment mcounter = tempcounter + 1; releasemutex(hmutexcounter); musedslots[tempcounter] = true; homecoming mpointers[tempcounter]; }

my error assert goes off in loop. question how prepare function , error caused multithreading?

edit: added mutex guard mcounter variable. no change. error still occurs.

i can't if error caused multi threading or not can code not thread safe.

you free lock

releasemutex(hmutexcounter);

and access tempcounter , musedslots:

musedslots[tempcounter] = true; homecoming mpointers[tempcounter];

neither of const. info race because have not correctly serialized access these variables.

change to:

musedslots[tempcounter] = true; const unsigned int retval = mpointers[tempcounter]; releasemutex(hmutexcounter); homecoming retval;

then @ to the lowest degree code thread safe, whether solves problem can't say, seek out. on machines multiple cores weird things happen result of info races.

as general best practice suggest looking @ c++11 synchronization features std::mutex , std::lock_guard, have saved self because std::lock_guard releases lock automatically can't forget and, in case, can't inadvertently. create code more portable. if don't have c++11 yet utilize boost equivalents.

c++ multithreading memory singleton manager

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -