Windows core programming note 4-Thread

Source: Internet
Author: User
ArticleDirectory
    • I. Compile thread functions:
    • 2. Create a thread kernel object:
    • 3. Terminate the thread
    • 4. Some thread Properties
    • 5. ID of the user
    • 6. Thread Scheduling
    • 7. Pause the thread
    • 8. Thread sleep
    • 9. Conversion thread
    • 10. Return the thread running time
Chapter 4: threads

As mentioned above, a process consists of two parts: a process Kernel Object and an address space. Likewise, a thread consists of two parts:
1. Thread kernel object.
2. The thread stack.

The features of a process are inactive, and it never executes anyCode. A process is only a container of a thread. The thread is always generated in the environment of a process, and its entire life is in the process. Pay attention to this relationship.
In a process, two or more threads can: Share the address space of a process, execute the same code, operate on the same data, and share the kernel object handle of the process.

Main thread: when a process starts, the main thread starts to run. Its life cycle starts from calling the entry point function winmain or main, until the function returns the C/C ++ Runtime Library to call the exitprocess function.

I. Compile thread functions:

The function code is as follows:

DWORD winapi threadfunc (pvoid pvparam)
{
DWORD dwresult= 0;

Return(Dwresult );
}

You can execute the task you want in.

Thread description:
1. The main thread name must be main or winmain, rather than others. You cannot customize the main thread function.
2. The thread must return a value as the exit code of the thread, and the main thread is no exception.
3. Use local variables or parameters as much as possible for thread functions. If static variables or global variables are used, other processes in the process can access and modify these variable values.

2. Create a thread kernel object:

The function prototype is as follows:Handle createthread (
Psecurity_attributes PSA,
DWORD cbstack,
Pthread_start_routine pfnstartaddr,
Pvoid pvparam,
DWORD fdwcreate,
Pdword pdwthreadid );

When the createthread function is called, The system creates a thread kernel object. Note: The thread kernel object is not the thread itself, but is used by the operating system to manage the data structure of the thread. The thread kernel object can be considered as a small data structure composed of thread statistics.
Then, the system allocates memory from the address space of the process for the thread stack to use. The thread can access the handles of all kernel objects in the process, all the memory in the process, and the stacks of other threads. It makes communication between multiple threads in a single process very easy.
Note: createthread is a Windows API function. If you use C/C ++ to write multiple threads, you should not use the createthread function, but use the C ++ Runtime library function _ beginthreadex.

Parameter introduction:
1. PSA: No need to introduce. Each kernel object has a security structure.
2. cbstack: set the number of address spaces that a thread space can use for its stack.
3. pfnstartaddr: Set the address of the thread function executed by the new thread.
4. pvparam: The parameter used by the thread function.
5. fdwcreate: Set the parameter used to control the thread creation. If it is set to 0, it indicates that the thread is created immediately. If it is set to create_suincluded, it indicatesProgramThis value is not commonly used to modify certain attributes of a thread before it has the opportunity to execute any code.
6. pdwthreadid: An address used to store the ID assigned to the new thread by the system.

3. Terminate the thread

1. Return of thread functions (recommended)
2. The thread is automatically revoked by calling the exitthread function.
3. Call the terminatethread function.
4. Process containing threads stops running.

Exitthread can cause this thread to terminate the operation immediately, but it cannot be confirmed that the C ++ resources are correctly released. Terminatethread can terminate any thread, as long as it passes in the thread handle to its parameters. The exitprocess of the root process is similar to the terminateprocess function.
After the terminatethread function is called, it is not guaranteed that the thread has been revoked because the function is an asynchronous function. If you need to know whether the function is revoked, you need to use the waitforsingleobject function.
Thread termination should be avoided using methods 2, 3, and 4.

4. Some thread Properties

1. Once the thread kernel object is created, the system allocates a stack to the thread from the address space of the process.
2. Each thread has its own CPU register, called the thread context. This context stores the status of the CPU registers that were saved when the last thread was running.
3. The instruction pointer and stack pointer are the most important registers in the thread context. Note: The thread always runs in the context.

5. ID of the user

Obtain
Functions can be used to obtain the ID of the process and the thread:
DWORD getcurrentprocessid ();
DWORD getcurrentthreadid ();
However, these two functions are pseudo handles for obtaining the ID. We can obtain the unique handle value of a process or thread, that is, using the duplicatehandle function:Bool duplicatehandle (
Handle hsourceprocess,
Handle hsource,
Handle htargetprocess,
Phandle phtarget,
DWORD fdwaccess,
Bool binherithandle,
DWORD fdwoptions );

For more information, see Chapter 6.

6. Thread Scheduling

Windows is a preemptible operating system. Therefore, the system can schedule and schedule threads. As mentioned above, each thread has a context that records the status of the registers of the last time the thread was running at the CPU. Every 20 ms, the system will view all the thread kernel objects. Among these objects, only some can be considered as schedulable objects. The system selects one and schedules it to the CPU. Then, the thread loads the saved context to each register and continues to run the Code completed at the end of the thread. After 20 ms, if the thread is not completed, the value of the Register is saved in the context of the thread, suspend the thread and select another schedulable thread. The system repeats this action until the system is shut down.

Windows is a preemptible type, indicating that a thread can be terminated at any time and a scheduling thread can be scheduled at any time. The program can be controlled and scheduled.

In Windows, many threads are non-scheduling threads. Why? Because many threads are waiting for an event. For example, if you run the notepad Notepad program but do not enter anything, it is useless to schedule the thread. You only need to type a value in notepad or move the notepad window, it can be changed to a scheduler. Also, if the pause count of some threads is greater than 1, it indicates that the thread has been paused and cannot be scheduled. You can create a pause thread by calling the CreateProcess or createthread function of the create_suspened mark.

7. Pause the thread

The thread's kernel object has a value indicating the thread's pause count. You can pause or restore a thread multiple times. The paused thread does not participate in CPU scheduling.
As mentioned above, you can create a pause thread in CreateProcess or createthread. In addition, you can also pause the created thread and use the suspendthread function to operate it:DWORD suspendthread (handle hthread );

Use the resumethread function to restore the thread:

DWORD resumethread (handle hthread );

Note: any thread can suspend other threads by calling suspendthread, so it must have the ID of other threads. The thread can automatically pause running, but it cannot resume running on its own.

8. Thread sleep

If you do not want a thread to be scheduled for a certain period of time, the thread can be sleep.

Void sleep (DWORD dwmilliseconds );

9. Conversion thread

The system provides the switchthread function so that another thread can be scheduled. Call this function to check whether there is a thread that requires CPU time slice. If so, the system schedules the thread. If not, returns false.
Function:

Bool switchtothread (); 10. Return the thread running time

Bool getthreadtimes (handle hthread,
Pfiletime pftcreationtime, pfiletime pftexittime,
Pfiletime pftkerneltime, pfiletime pftusertime );

Four values are returned: Creation Time, exit time, Kernel Time, and user time.
Note: getprocesstimes is a function similar to it and applies to all threads in the process:Bool getprocesstimes (handle hprocess,
Pfiletime pftcreationtime, pfiletime pftexittime,
Pfiletime pftkerneltime, pfiletime pftusertime );

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.