WIN32 Threads Flashcards
WaitFor{Single|Multiple}Object(s)
Single:
- hObject
- dwTimeOut: if zero, returns immediately after the state of the object has been tested.
Multiple:
- nCount: cannot exceed the maximum (usally 64)
- lpHandles: array of handles of objects to wait for
- fWaitAll: if true, waits for all the objects in the array (at most 64), otherwise asa one gets released
- dwTimeOut
Possible return values:
- WAIT_OBJECT_0: for WFSO or WFMO when fWaitAll is true.
- WAIT_OBJECT_0 + n (where 0 <= n <= nCount): thanks to this it is possible to determine the index of the object that just terminated in the array passed.
- WAIT_TIMEOUT: timeout elapsed before the object was released
- WAIT_FAILED: the call to wfso or wfmo failed
- WAIT_ABANDONED_0: used for mutex handles
Waiting on more than 64 objects
Wait for all the first group, then go to the next
for(i = 0; i < N; i+=MAXIMUM_WAIT_OBJECTS)
WaitForMultipleObjects(min(MAXMIMUM_WAIT_OBJECTS, N-i), &threadH[i], TRUE, INFINITE);
Sliding window waiting
while(N > 0) {
return_val = WaitForMultipleObjects(min(MAXIMUM_WAIT_OBJECTS, N), threadH, FALSE, INFINITE);
index = (int) return_val - (int) WAIT_OBJECT_0;
CloseHandle(threadH[index]);
…
threadH[index] = threadH[N-1];
… Free threadData …
threadData[index] = threadData[N-1];
N–;
}
CreateThread
include
CreateThread:
- lpsa
- dwStackSize: byte size for new thread stack (0 for default)
- lpStartAddr: pointer to function
- lpThreadParm: pointer passed as thread argument
- dwCreationFlags
- if 0 -> immediately run
- if CREATE_SUSPENDED the new thread will need to be resumed (ResumeThread) to run)
- lpThreadId points to DWORD that received threadId
Thread identifiers
Terminated threads will exists until their handle will be closed.
Other threads can retrieve exitcodes of terminated threads.
Threads can retrieve informations about others.
Resume and suspend
- Resume
- Suspend
Threads can increment or decrement suspend count of another thread.
Both resume and suspend return the previous suspend count;
This techiniques are not safe for general synch. but useful to avoid some race conditions.
Thread priority
- It is possible for a thread to change or to determine a thread’s priority, either from the same process or from another.
- Thread priorities are relative to the process base priority.
- Avoid real time properties for user processes, be carefult with high priorities, ensure fairness!