c++ - Is CRITICAL SECTION required? -
i got code below google search trying learn multithreading. run code critical section used , without critical section, after executing both situations, don't understand why author of code uses critical section.
static unsigned int counter = 100; static bool alive = true; critical_section cs; static unsigned __stdcall sub(void *args) { while(alive) { entercriticalsection(&cs); cout << "[sub(" << counter << ")]---" << endl; counter -= 10; leavecriticalsection(&cs); sleep(500); } return 0; } static unsigned __stdcall add(void *args) { while(alive) { entercriticalsection(&cs); cout << "[add(" << counter << ")]+++" << endl; counter += 10; leavecriticalsection(&cs); sleep(500); } return 0; } int _tmain(int argc, _tchar* argv[]) { initializecriticalsection(&cs); unsigned add; handle hadd = (handle)_beginthreadex(0,0,&add,0,create_suspended, &add); assert(hadd != 0); unsigned sub; handle hsub = (handle)_beginthreadex(0,0,&sub,0,create_suspended, &sub); assert(hsub != 0); //start threads resumethread(hadd); resumethread(hsub); //let threads run 10 seconds sleep(3000); alive = false; waitforsingleobject(hsub, infinite); closehandle(hsub); waitforsingleobject(hadd, infinite); closehandle(hadd); return 0; }
a critical_section simple sync mechanism multi-threaded. use critical_section protect block of code having 2 or more threads running @ same time.
you not see difference, or without in cases, there protected shared resources getting run on example:
imagine 2 threads accessing resource block of memory @ same time, 1 reading image while other writing image it. reading thread corrupt image.
i suggest more reading on multi-threaded better understand concepts , how use synchronization objects control flow in multi-threaded applications.
Comments
Post a Comment