Be careful with multithreaded programming (1)

Source: Internet
Author: User

Recently I have had a lot of ideas and want to thoroughly understand all the things I have used, so that it will not become the so-called "samples are similar ". I'm a newbie. Please let me know if you have any problems. Thank you!

In fact, I originally wanted to use my blog as my own diary and record what I learned. What I wrote represents what I learned. People say that good memory is not as good as bad writing.

I have been confused about multithreading for a long time. I don't use much of it. Even if I use it, I also take out the previously written code and modify it slightly to meet new requirements. I have read some materials, but I have never practiced it. So I have to be able to adapt to my work needs. In fact, this idea is very wrong. You must be steadfast in technology; otherwise, you will not be able to grow.

In the next few articles, I will learn and summarize the multi-threaded things. First, the first paragraph of the gold oil:
Thread: a Lightweight Process (LWP) is the smallest unit of execution flow. A standard thread consists of the thread ID, current Instruction Pointer (PC), register set, and stack. In addition, a thread is an entity in a process and is the basic unit for independent scheduling and distribution by the system. A thread itself does not own system resources, but only has a few resources that are essential for running, however, it can share all resources of a process with other threads of the same process. One thread can create and withdraw another thread, and multiple threads in the same process can execute concurrently. Due to mutual constraints between threads, the threads are intermittently running. The thread also has three basic states: Ready, blocked, and running. Each program has at least one thread, that is, the program itself.

Since the thread is available, this world has become noisy, including thread cycle, scheduling and priority, resource sharing, thread synchronization, daemon thread, deadlock, and semaphores .. Let's take a closer look at these things later. Today, we will briefly understand what the thread is and how to apply it to programming.

The old practice is to use the previous program. Create a standard dialog box-based MFC program, drag an edit control and a button on it, and name the resource ID_EDIT_NUMBER and ID_BUTTON_START respectively. Associate the edit Control with the variable CEdit * m_editNumber. Just like this.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1A51060A-0.png "border =" 0 "alt =" "/>

First, write a thread function to tell the computer what to do in this thread.

 
 
  1. DWORD _stdcall ThreadProc(LPVOID lpParameter) 
  2.     CMultithreadTestDlg * dlg = (CMultithreadTestDlg*) lpParameter; 
  3.     CString szCounter; 
  4.  
  5.     for(int i = 0; i < 10000; i++) 
  6.     { 
  7.         szCounter.Format(_T("%d"), i); 
  8.         dlg->m_editNumber.SetWindowTextW(szCounter); 
  9.         szCounter.ReleaseBuffer(); 
  10.     } 
  11.  
  12.     return 0; 

It is easy to make the edit control display increasing numbers.

Next we will try to start this thread.

Add a member variable HANDLE m_hThread to CMultithreadTestDlg. Double-click the start button to edit the Click Event of the button.

 
 
  1. void CMultithreadTestDlg::OnBnClickedButtonStart() 
  2.     // TODO: Add your control notification handler code here 
  3.     m_hThread = CreateThread(NULL, 0, ThreadProc, this, 0, NULL); 

The following is a prototype of the CreateThread function:

 
 
  1. HANDLE WINAPI CreateThread( 
  2.   __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes, 
  3.   __in       SIZE_T dwStackSize, 
  4.   __in       LPTHREAD_START_ROUTINE lpStartAddress, 
  5.   __in_opt   LPVOID lpParameter, 
  6.   __in       DWORD dwCreationFlags, 
  7.   __out_opt  LPDWORD lpThreadId 
  8. ); 

The first parameter is a Security Attribute pointing to a structure of the LPSECURITY_ATTRIBUTES type, which is generally set to NULL;

The second parameter is the thread stack size. If the memory is not very tight, it is set to 0, indicating that windows will dynamically adjust the stack size;

The third parameter is the pointer to the thread function, which is actually the function name. The function name can be used at will, but the form must be followed when the function name is used.

 
 
  1. DWORD WINAPI ThreadProc(LPVOID lpParameter)  

Otherwise, the call fails;

The fourth parameter is the parameter passed to the thread function. If it is not passed, it is set to NULL;

The fifth parameter is the thread sign, which has two optional values:

1). create_suincluded, indicating that it will be suspended immediately after creation

2). 0, indicating normal creation and running immediately after creation

The sixth parameter is used to save the ID of the new thread. If you do not need to process the thread ID, NULL can be input.

The return value is the thread handle.

The running time is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1A5101K5-1.png "border =" 0 "alt =" "/>

This program is actually risky, and there are two risks:

1). In the MFC program, try to use the AfxBeginThread method to create a thread.

2) if I keep pressing start, the memory will be used up in a moment =. =

The solution of 2 is no longer available. It is nothing more than using a flag. No new thread is created before the thread is finished.

AfxBeginThread. This is a safer thread creation method in MFC. The function prototype is as follows:

 
 
  1. CWinThread* AfxBeginThread( 
  2.    AFX_THREADPROC pfnThreadProc, 
  3.    LPVOID pParam, 
  4.    int nPriority = THREAD_PRIORITY_NORMAL, 
  5.    UINT nStackSize = 0, 
  6.    DWORD dwCreateFlags = 0, 
  7.    LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL  
  8. ); 
  9. CWinThread* AfxBeginThread( 
  10.    CRuntimeClass* pThreadClass, 
  11.    int nPriority = THREAD_PRIORITY_NORMAL, 
  12.    UINT nStackSize = 0, 
  13.    DWORD dwCreateFlags = 0, 
  14.    LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL  
  15. ); 

There are two functions that can be reloaded. The first function is commonly used. It can also be seen that the parameters of the first function and CreateThread () are similar, but the order is not the same. Note that The second overload function is called. The first parameter is CRuntimeClass * pThreadClass, and CRuntimeClass is a struct. The explanation in MSDN is "The RUNTIME_CLASS of an object derived from CWinThread. for this reason, I specially read the source code of AfxBeginThread, including the following line:

 
 
  1. ASSERT(pThreadClass->IsDerivedFrom(RUNTIME_CLASS(CWinThread))); 

RUNTIME_CLASS is a macro definition.

 
 
  1. #define RUNTIME_CLASS(class_name) (class_name::GetThisClass()) 

This macro is used to convert the Thread class pointer to the object pointer pointing to CRuntimeClass.

Then the new thread creation statement is changed:

 
 
  1. CWinThread * m_thread; // m_thread is a member variable.
  2. M_thread = AfxBeginThread (ThreadProc, this );

In addition, you need to modify the declaration of the thread function:

 
 
  1. UINT ThreadProc(LPVOID lpParameter) 

The thread execution can be paused. Use the DWORD CWinThread: SuspendThread () function. After being paused, you can use the DWORD CWinThread: ResumeThread () function to resume the thread running.

This is a basic usage. As for some advanced things, James continues.

PS: the more you know, the less you know. Today, you can search for materials and find many things you have never heard. =, All in the book, one by one ..

PSS: the next goal. You can see what is associated with this webpage .. Http://en.wikipedia.org/wiki/Thread_ (computing)

PSSS: this is a real image ..

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1A5106403-2.png "border =" 0 "alt =" "/>

 

This article from the "front of the tradeford reverse tairuibao blog, please be sure to keep this source http://serious.blog.51cto.com/242085/857669

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.