Title: Threads
1Threads
2Threads
- Multiple threads of execution in a single process
- Threads have own stack, own local variables
- Threads share global objects
- Must share global objects in a controlled way, as
order of thread execution is non-deterministic
3C/Win32
const int MAX_NUM_THREADS 63 // NT Wait for
threads call breaks after 64 threads!! HANDLE
threadsMAX_NUM_THREADS / Array of worker
threads / // Global thread-safe
timers TPerfTimer tCreateT ("Create Account
Timer") int main(int argc, char argv) //
coming soon
4C/Win32
//get number of threads to start int i,
numThreads DWORD tid numThreads
atoi(argv2) assert (numThreads ! 0) assert
(numThreads lt MAX_NUM_THREADS ) // start
threads.. for (i0 ilt numThreads i
) threadsiCreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)doSubClient,
(LPVOID) i , 0, (LPDWORD)tid) // end
for // wait for all threads to
finish WaitForMultipleObjects(numThreads,
threads, TRUE, INFINITE) // tNST.results() tCre
ateT.results(0)
5C/Win32
void doSubClient (void arg) TRACE
("doSubClient Entry" ) start GetTickCount()
subObj.CreateAccount (subInfo, subAccNo )
end GetTickCount() tCreateT.AddSample (
end - start ) // etc TRACE ("doSubClient
Exit" )
6C
- On Solaris, can use
- Solaris native threads
- pthreads
- or Java...
7Java
public class Client implements Runnable //
Result log instances ResultLog resultLogByCode
new ResultLog() public static void
main(String args) if (args.length ! 1)
System.out.println("You need to specify the
number of thread.") return // Get the
number of threads to be started int threadCount
Integer.parseInt(args0) // To save the thread
objects, so that we can wait for them. Thread
threadArray new ThreadthreadCount //
continued
8Java
// Note We only create one object of the
Runnable (Client) class // and we pass
this object to all the Thread instances. Client t
new Client() // Start the threads here for
(int i 0 i lt threadCount i)
threadArrayi new Thread(t) threadArrayi
.start() // Wait for the threads to
terminate for (int i 0 i lt threadCount i)
try threadArrayi.join() catch
(InterruptedException e) System.out.println(
"All threads are finished.") // Print the
result System.out.println(resultLogByCode.getAvera
ge())
9Java
public void run() startTime
getCurrentTime() qr broker.queryStockValueByID(
tranInfo.stockID) // Transaction endTime
getCurrentTime() resultLogByCode.addSample(endTim
e - startTime) //etc
10Protecting shared values
- Need to serialize access to shared objects when
we change their state - easy in Java
- use mutexes or critical sections in C