【正文】
proposed to achieve this by having multiple processes ? However, it was soon found that the overhead (. the time required) for switching between processes is very high ? Besides, processes are not tightly coupled to one another, it is difficult to share resources, such as open files ? They motivate the idea of further dividing a process into smaller units, . threads 8 ? A puter has only one CPU, which can execute one program at a time ? Hence, in reality, threads are not executing at the same time, but alternatively one after the other ? For a multithreading system, a thread has at least the following three states: Ready Running Sleeping Start execution Finish execution Department of ELECTRONIC AND INFORMATION ENGINEERING 3. Controlling Robot Car by Wireless Sensor by Dr Daniel Lun How Threads Are Executed? 9 ? Ready state – All threads that are ready to execute but without the CPU are at the ready state – If there is only 1 CPU in the system, all threads except one are at the ready state ? Running state – The thread that actually possesses the CPU is at the running state – If there is only 1 CPU in the system, at most there is only one thread is at the running state ? Sleeping state – The process that is waiting for other resources, . I/O or a preset time, is at the sleeping state Department of ELECTRONIC AND INFORMATION ENGINEERING 3. Controlling Robot Car by Wireless Sensor by Dr Daniel Lun 10 ? Threads will alternatively get into the CPU one after the other (called the round robin scheme) ? At the time that a thread is selected to be “in” the CPU – It goes from ready state to running state ? After that, it will be swapped out – It goes from running state back to ready state ? Or it may due to the waiting of a preset time – It goes from running state to sleeping state ? When timeup – It goes from sleeping state to ready state Department of ELECTRONIC AND INFORMATION ENGINEERING 3. Controlling Robot Car by Wireless Sensor by Dr Daniel Lun 11 Implementation CreateThread HANDLE CreateThread ( LPSECURITY_ATTRIBUTES lpsa, DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddr, LPVOID lpvThreadParm, DWORD dwCreationFlag, LPDWORD lpThreadId )。 bool *pExit。 while (true) { pLatusUpdatePO()。ThreadId)。 } Assume pExit is a pointer of a shared variable which will be updated by a thread outside. If that thread wants this thread to terminate, it just needs to change such variable to TRUE 20 Department of ELECTRONIC AND INFORMATION ENGINEERING 3. Controlling Robot Car by Wireless Sensor by Dr Daniel Lun Thread A Thread B CreateThread(…