110 likes | 258 Views
Lab3. TA: Yi Cui 02/12/2013. Part 3. Goals Practice multiple threads programming Difficulties Synchronization Exit condition. Part 3. What does the big picture of part 3 look like? Your threads CC process Robots. Synchronization. Use critical section to protect shared data
E N D
Lab3 TA: Yi Cui 02/12/2013
Part 3 • Goals • Practice multiple threads programming • Difficulties • Synchronization • Exit condition
Part 3 • What does the big picture of part 3 look like? • Your threads • CC process • Robots
Synchronization • Use critical section to protect shared data • Notification of exit • Program termination
Critical section • Where do we need to use critical section? Search() { U.add (s, 0); D.add (s); while ( U.notEmpty () ) t = U.removeNextTuple () if ( t.ID == T ) break N = G.getNeighbors (t) for each y in N if ( D.find (y) == false ) U.add (y) D.add (y) }
Exit condition • Find exit • No more nodes to be searched • U is empty • No active threads • What is an active thread?
Notification of exit • Set a boolean flag: exit = true, false ? • Set event ?
Program termination HANDLE *hSearch = new HANDLE[robot]; for (int i = 0; i < robot; i++) hSearch[i] = CreateThread(...); // wait for all threads to finish for (int i = 0; i < robot; i++) WaitForSingleObject(hSearch[i], INFINITE); DisconnectRobots(...); DisconnectCC(...);
Passing parameters (C style) struct Parameters { HANDLE mutex; U D int activeThread; int totalExtracted; }; DWORD WINAPI SearchThread(LPVOID lpPara) { Parameters *p = (Parameters*)lpPara; p->U ... } Parameters para; handles[i] = CreateThread(..., SearchThread, ¶, ....);
Passing parameters (C++ style) class GraphSearch { public: void search(); private: HANDLE mutex; int totalExtracted; ... }; DWORD WINAPI SearchThread(LPVOID lpPara) { GraphSearch *p = (GraphSearch*)lpPara; p->search(); ... } GraphSearch gs; handles[i] = CreateThread(..., SearchThread, &gs, ....);
Misc • Suppose we have 5,000 threads • Where do we create 5,000 pipes? • Where do we do 5,000 initial connection? • Initial room is always the same • Shared data • Pass by reference (do not make multiple copy of it)