Windows multithreaded simple learning for the operating system

Source: Internet
Author: User
Tags terminates

    1. Operating system courses in the course of learning, ....... First understand what is a handle.

      A handle is a pointer to a pointer. We know that the so-called pointer is a memory address. after the application is started, the objects that make up the program are left in memory. If we simply understand, it seems that we just know the first address of this memory, then we can access the object at any time with this address. But if you really think so, then you're wrong. We know that Windows is a virtual memory-based operating system. In this system environment, the Windows Memory manager often moves objects back and forth in memory to meet the memory needs of various applications. The object being moved means that its address has changed. If the address always changes so, where should we go to find the object?
      To solve this problem, the Windows operating system frees up some internal storage addresses for each application to specifically register the address changes in memory for each application object, and the address (the location of the storage unit) itself is unchanged. When the Windows Memory Manager moves the object's location in memory, it stores the address of the new object to the handle. So we just have to remember this handle address to know indirectly where the object is in memory. This address is assigned by the system when the object is loaded (load) and released to the system when the system is unloaded (Unload).

    2. Handle address (Stable) → The address of the object in memory → The address of the object in memory (unstable) → actual object

    3. The relationship between a thread and a handle:

      A handle can be thought of as a number assigned by the system to a resource (such as a thread). Close this number, for different resources, the effect is not the same. For threads, closing this number does not mean terminating the thread, but it is difficult to manipulate it later.

    4. The difference between a thread handle and a thread ID:

The CreateThread () API is used to create threads. The API returns both the thread handle and the thread identifier (ID). The thread handle has full access to the Create thread object. The thread ID uniquely identifies the thread at the system level when the thread is running.

1) The ID is the only thread that is uniquely labeled in Windows system scope.

2) handle is used to operate the thread, can have more than one, each handle can have a different operation permissions, in different processes openthread The value is not the same.

3) The ID of the thread is the system global, and its handle is local to the process.

4) Handle is a bridge between the OS and the client used to manipulate processes and threads, and the OS has a form for maintaining handle, which presumably places the handle reference count and related properties, handle is the OS identity process and thread thing, However, the user can also use this to identify processes and threads, and the ID is used by the OS to identify processes and threads, and is globally unique, but the user can get the handle of the process thread through this ID, and the handle is not necessarily the same. Handle is a kernel object, The ID does not seem to be, and there is no function to create the ID specifically.

5) The ID is createthread when the operating system is automatically generated.

6) the handle and ID of the thread are different.
In Windows systems, the ID of a thread is unique, that is, if two threads return the same ID, they must be the same thread, and vice versa. The handle of a thread is not a thread's unique identity, and the handle of the thread is only used to access a 32-bit value of the thread, although the same handle must identify the same thread, but it may have two open handles, so it is not possible to use a handle to differentiate whether two threads are identical.

When the thread terminates the run, the following actions occur:
1. All user objects owned by the thread are freed. In Windows, most objects are owned by the process that contains the threads that created those objects. However, a thread has two user objects, namely windows and hooks. When the thread terminates the run, any windows are automatically undone and any hooks created or installed by the thread are unloaded. Other objects are revoked only if the process that owns the thread terminates the run.


2. The exit code for the thread changes from still_active to the code passed to ExitThread or TerminateThread.
3. The state of the thread kernel object becomes notified.
4. If the thread is the last active thread in the process, the system also treats the process as if it had been terminated.
5. The usage count of thread kernel objects is decremented by 1.
  When a thread terminates the run, the kernel object is not automatically freed until all the closed references to the thread kernel object associated with it are shut down.


Once the thread is no longer running, no other thread in the system can handle the thread's handle. However, other threads can call GetExitCodeThread to check whether the thread identified by Hthread has terminated. if it has stopped running, determine its exit code:

The value of the exit code is returned in the DWORD that Pdwexitcode points to. If the thread has not been terminated while calling GetExitCodeThread,//The function fills in a DWORD with the still_active identifier (defined as 0x103).  Returns TRUE if the function runs successfully. BOOL GetExitCodeThread (HANDLE hthread, pdowrd pdwexitcode);


The Kernel object is fired when the thread exits, WaitForSingleObject () is a blocking function, and the kernel object waiting for the thread is fired.

so the order of terminating the thread and releasing the handle object is:

TerminateThread ()-->waitforsingleobject ()-->closehandle ().

Thread, thread handle, thread ID generation and disappearance hthread = CreateThread (null, 0, threadproc, NULL, 0, &DWID); At this point, the new thread, thread handle, thread ID produces terminatethread (hthread, 0); At this point, the thread ID, thread handles are still present WaitForSingleObject (Hthread, INFINITE);  At this point, the thread itself and the thread ID disappear CloseHandle (hthread); At this point, the thread handle is eliminated

Note:

    dword WaitForSingleObject (HANDLE hhandle, DWORD dwmilliseconds);
     parameters:
             Hhandle[in] Object handle. You can specify a range of objects, such as event, JOB, Memory resource notification, Mutex, Process, Semaphore, Thread, waitable timer, and so on.

            dwmilliseconds[in] timing interval, The unit is milliseconds (milliseconds). If you specify a value other than 0, the function waits until the Hhandle tag object is triggered, or the time is up. If Dwmilliseconds is 0, the object is not signaled, and the function does not enter a wait state, and it always returns immediately.

            // 2015-10-15//  Create two threads for simple printing   hello#include<windows.h> #include <iostream.h> //  define two thread functions write () and read ()// The  read (), Write () functions use the VC + + p, v Operation WaitForSingleObject () and ReleaseSemaphore () Dword winapi write respectively ( Lpvoid lpparameter);D word winapi read (lpvoid lpparameter); //  buffer resource unsigned  char buffer; //  two semaphores, using two resources in buffer buffers: Full and empty// semaphore1  indicates buffer full, initial value is 0, The maximum value is 1// semaphore2 , which indicates that buffer is NULL, the initial value is 1, and the maximum value is 1handle semaphore1; handle semaphore2; //Thread Handle  handle hthread1; handle hthread2; void main ( ) {      // buffer empty     buffer= '   ';     //  Create Semaphore     semaphore1=createsemaphore (null,0,1,null);     semaphore2=createsemaphore (null,1,1,null);      //  Create a thread CreateThread function creates a thread,  the system internally has a handle to the thread,  also returns a handle to the user .            hthread1=createthread (null,0,write,null,0,null);     hthread2=createthread (null,0,read,null,0,null);     //  cannot exit the thread before the child thread finishes executing. Otherwise display result exception     sleep (10000);     //  close handle     CloseHandle (handle h) closes the handle, preventing the memory leak by inadvertently shutting it down for forgetting.               closehandle (Write);     closehandle (Read);     //  release signal Volume      CloseHandle (Semaphore1);     closehandle (Semaphore2);} The write  is responsible for writing a character to the buffer each time    read is responsible for extracting one character from the buffer each time   //  thread 1 corresponds to the P function entity: Buffer Cache write operation   Dword winapi write (lpvoid lpparameter) {    unsigned char str[6]= " Hello ";     int i=0;    for  (i=0;i<5;i++) {         //  Wait buffer empty         waitforsingleobject (  semaphore2, infinite );        //  buffer is empty, write data to buffer          buffer=str[i];        //   Notification buffer full         releasesemaphore ( semaphore1, 1,  null );     }    return 0;}  //  thread 2 corresponds to the V function entity: Buffers Buffer read Operation Dword winapi read (Lpvoid lpparameter) {     int i=1;    unsigned char c;    for  (i=1;i <=5;i++) {        //  waiting buffer full              //  The second parameter is  infInite, which indicates that the function will not return until the object is signaled.          waitforsingleobject ( semaphore1, infinite);         //  get data from cache buffer          c=buffer;        //  output data extracted from buffer buffers          cout<<c;        //  Notification buffer empty         releasesemaphore ( semaphore2, 1, null  );    }    //  carriage return line     cout<<endl;     return 0;  }

Windows multithreaded simple learning for the operating system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.