Basic knowledge and simple application of threads in Windows ---- THREAD's life and death

xiaoxiao2021-03-05  36

A new project began in April, need to enable multithreading. I have also done such a project before, but I just came out from the school, I didn't know anything, and I wrote a letter. Today, it is necessary to "retreat the old industry". Oh, although it is not more than the past, it doesn't dare. Know more, it is more clearly of the complexity. Because this project cannot be tested in the company, it is best to write rigorous, thoughtful, and avoid a lot of modifications. So, come out of several "secret", revisit, ready to do one.

Turning out the textbook in the bottom of the box, the thread is only introduced in the last section of the process, and the total is 4 pages. This 4 pages are similar to thread-related concepts, and very concise. It is also no wonder that it is always necessary, so complicated things are "showing the style" in these 4 pages, but it is a good job. However, if you deal with the exam, you should be another matter.

If you talk about the thread, you can't talk about the process. The process is a running program instance that contains resources and memory. When a process is executed, it automatically creates a thread, which is the main thread, and then this main thread can create other threads. The process is lively, it is thread to execute the code included there. We can also say that the process does not perform anything, it is just a container containing threads. If there is N threads in a process, this n thread sharing process is all resources. Therefore, the thread object within the process can share resources in this process so that multi-threads in the unified process can be easily communicated.

The thread contains two parts, one is a kernel object, the operating system can be managed by it; the other is the thread stack for maintaining all the functions required for the thread to execute the code.

Many people will have such a question, why don't there be more processs? First, the thread is the basic scheduling singles, the resources occupied, can share system resources; secondly, this is the resource in the process is not shared, which is also the most important.

In today's software, the use of multi-threads is everywhere. Document writing software, users are constantly type characters, software is not stopping spelling and syntax errors; in burning software, software background is running, and users can still operate the software. In fact, both software have used multi-threaded technology, and a thread is responsible for errors in language, and a thread is responsible for burning. If there is no multi-thread existence, then the user can only wait for the software to check the language errors, or the user can only operate the burning software only after the user is waiting for the burning.

So, is there a multi-thread, is it used after using multiple threads, is the execution speed of the software has improved. This is actually not the case. Quote One sentence in "in-depth MFC", "Multi-threading does not allow the program to perform a relatively fast (unless you use the operating system that supports Symmetric Multiprocessingde), it is only possible to compare [reactive] ".

You can create a thread with the CreateThread function in the Win32 operating system.

Handle CreateThread

LPSecurity_attributes LPTHREADATIADATTRIBUTES,

Size_t dwstacksize,

LPTHREAD_START_ROUTINE LPSTARTDRESS,

LPVOID LPPARETER,

DWORD DWCREATIONFLAGS,

LPDWORD LPTHREADID

);

When this function is called, a thread kernel object is created. Thread kernel objects are not thread itself, but the operating system used to manage the smaller data structure of the thread. The system is allocated from the address space of the process, and the stack for threading is used. LPTHREADATTRIBUTES is a security_attributes structural pointer, which is responsible for the security properties of the kernel. In most cases, it is like NULL. DWSTACKSIZE Sets how much address space has a stack of this thread as its own stack. The default is 1MB. When the thread stack overflows, the system will throw an exception. So, when you assign a thread stack, you need to use it. LPStartAddress wants the address of the thread function that thread executes. This thread function requires a specific format, such as: DWORD WINAPI ThreadFunc (LPVOID PVPARAM). LPPARAMETER pass the parameters of the thread function. This parameter is the parameter LPVOID PVPARAM in the above thread function. DWCREATIONFlags sets other signs for creating threads. This identity can control the thread after being created or is still in a paused state. The LPTHREADID system is assigned to the thread. The thread ID can be used as a unique identifier within the operating system.

CreateThread will return the handle of the thread after CreateTHREAD. This handle is called a core object. I

They can operate this thread by it.

Since the thread ID can be used as a unique identifier in the operating system, it will naturally think

The handle of the thread can be obtained by the thread ID. But it is actually not done, this is for security

The protection measures taken are taken.

Let us look at an example now:

First, build two thread functions as follows:

DWORD WINAPI Threadfunc_one (LPVOID PPRAM)

{

_cwprintf (_t ("% s / n"), _t ("Hello, I am frist thread."));

Return 0;

}

DWORD WINAPI ThreadFunc_Two (LPVOID PPRAM)

{

_cwprintf (_t ("% s / n"), _t ("Hello, I am Second Thread."));

Return 0;

}

Then, we create two threads in the main function, as follows:

Handle HHAND_ONE = :: CreateThread (Null, 0, Threadfunc_one, Null, True, 0);

Handle HHAND_TWO = :: CreateThread (Null, 0, Threadfunc_Two, Null, True, 0);

Oh, run a procedure. What kind of results will it produce? ......

...............

...............

...............

-

One and expectation, very satisfied.

Let's run again.

...............

....................

...............

-

% ¥ @ # ¥ ...... &% ^ # $ ......... V_V This is a stuff. It's not wrong.

Again!

...............

....................

...............

-

% ¥ @ # ¥ .... &% ^ # $ ......... * _ * is this Dongdong.

Come!

Come!

Come!

% ¥ @ # ¥ .... &% ^ # $ ......... @ _ @ 无 了!

This is the characteristics, randomness, and disorder of threads. So, when using multi-thread, you must coordinate.

For me, don't create a few threads, turn into a mess. As for how to manage threads, it will be said later.

There is a life, and there is a dead. What is the thread die?

The thread is still a very good little thing. When it completes his own mission, he ends his life. However, it is not good to be good at all times. How to be threads to kill (a little violent), we need two functions to complete this mission. EXITTHREAD and TERMINATTHREAD These two functions are threaded killers.

Void WinApi Exitthread (DWORD DWEXITCODE)

Bool WinApi TerminateThread (Handle Hthread, DWORD DWEXITCODE)

Use these two functions to end the life of the thread, not only violence, and it is not a good way.

The ExitThread function can immediately terminate the created thread and make the operating system clear the thread to occupy the resources of the operating system. However, it cannot be emptied.

The TerminateThread function can terminate any thread. Since the function is asynchronous, it is not possible to ensure that the thread has been terminated after the function returns. Further, the operating system cannot release the thread stack of the termination thread before the end of the process of the termination thread is terminated.

So, these two functions are easy to use, it is best not to be called. The killer must be snow hide O (∩_∩) o .... As developers must try to ensure that the thread can automatically terminate, not the external force to end the thread's life.

After the thread ends life, we have to do something. It is revoked its account. Call the CloseHandl function telling the operating system to prepare to revoke this thread object.

Bool WinApi CloseHandle (Handle Hobject);

The operating system will reduce the counter of the thread kernel object 1. This thread object is really cleared when the reference counter of the thread core object is reduced.

In fact, when creating a thread, the default value of the reference counter of thread object is 2. When the thread function performs the end returns, the value of the reference counter is 10. After the CloseHandle function is called, the value of the reference counter will drop 1.

Of course, we can also call the CloseHandle function to notify the operating system immediately after the CREATHREAD function is successfully created.

When you create a function using the CreateThread function, the DWCreationFlags flag has been set to True, then start executing immediately after the thread is created. But many times we don't want the thread to execute immediately, then set the dwcreationFlags flag bit_suspended when creating a thread. At this time, the thread creates the end of the pause, waiting to be awake.

There is a thread pause counter on the thread core object. This counter records the pause count value of the thread, only when the value is 0, the thread is awakened. This pause count is 1 when CreateThread creates a thread. After the thread initialization is complete, it is to determine if the creator has passed the create_suspended identity. If there is no incoming, the counter value is decremented to 0.

When the thread is paused, you can use the ResumeThread function to wake up the thread. After this function is successfully run, the value of the thread pause counter is reduced by 1.

DWord WinApi ResumeThread (Handle Hthread);

Compared with the ResumeThread function is the SuspendThread function. It allows the running thread to be suspended. but,

Be careful when using the SuspendThread function because it is easy to cause the deadlock to cause the program to exception.

DWORD WINAPI SUSPENDTHREAD (HANDLE HTHREAD);

转载请注明原文地址:https://www.9cbs.com/read-31925.html

New Post(0)