Introduction to "multithreading" and Its C code implementation framework

Source: Internet
Author: User

Introduction to "multithreading" and Its C code implementation framework

In some books related to computer science, we often hear about the concept of "multithreading. So what is "multithreading "? When can I use multiple threads "? What are the benefits of using multiple threads in programming? Many new programmers are also very curious about multithreading and think it is "too tall ". This article briefly introduces "multithreading" and provides the implementation framework of its C code.

"Single thread" program
To understand "multithreading", we must start with "single thread.
As we all know, the process in the "assembly line" of the factory is a link, and the next process can be started only after the previous process is completed. This is actually very similar to the principle of "single thread.
In a single thread, the functions of the program are executed sequentially. Only when the previous process is successfully executed can the subsequent process be executed. For example, to implement a program for generating, uploading, and deleting a single-threaded file, use the "single-threaded" program. The process 1 is shown in.

Figure 1 "single thread" program

Multi-thread Program
You may have noticed that the process of generating, uploading, and deleting files in Figure 1 can be independent. That is to say, these three processes do not affect each other. In this way, the concept of "multithreading" is born.
Multiple Threads, as the name implies, are multiple "single Threads". Each thread independently completes related functions. If the program shown in 1 is implemented using multiple threads, its process 2 is shown.

Figure 2 multi-threaded Program

As shown in figure 2, after the program is started, thread 1, thread 2, and thread 3 run simultaneously. Thread 1 is only used to generate a ticket file, thread 2 is only used to upload a ticket file, and thread 3 is only used to delete an expired ticket file. In this way, the successful execution of any thread has no impact on the other two threads, truly implementing the "Parallel" of the program ".

Advantages of multiple threads
Multithreading is widely used in large-scale software programs. Its advantages are as follows:
First, put the functions originally implemented in a large process into multiple small processes, and the program is more concise and easy to read.
Second, different functions are put into different threads, which improves the execution efficiency of the program.
Third, multithreading makes the program more modular and facilitates tracking the Program Execution Process and troubleshooting.

Multi-threaded C code framework

/*************************************** * ******************************** All Rights Reserved (C) 2015, Zhou Zhaoxiong. ** File name: ThreadCreate. c * File ID: none * Content Abstract: demonstrate multi-thread creation * Other Instructions: none * Current version: V1.0 * Author: Zhou Zhaoxiong * completion date: 20151029 *************************************** * *******************************/# include
  
   
# Include
   
    
# Include
    
     
// Redefine the Data Type typedef signed int INT32; typedef unsigned int UINT32; // macro definition # define THREAD_NUM 5 // Number of threads // function declaration void ScanTask (void * pParam ); void ProcessTask (void * pParam ); /*************************************** * ******************************** function description: main function * input parameter: none * output parameter: none * return value: none * Other description: no * modified date version number modifier content * --------------------------------------------------------------------------- * 20151029 V1.0 Zhou Zhaoxiong creation *** **************************************** * **************************/INT32 main () {pthread_t MultiHandle = 0; // multithreading handle pthread_t SingleHandle = 0; // single thread handle UINT32 iLoopFlag = 0; INT32 iRetVal = 0; // create the return value of the thread function // create the thread cyclically for (iLoopFlag = 0; iLoopFlag <THREAD_NUM; iLoopFlag ++) {iRetVal = pthread_create (& MultiHandle, NULL, (void * (*) (void *) (& ScanTask), (void *) iLoopFlag); if (0! = IRetVal) {printf (Create ScanTask % d failed !, ILoopFlag); return-1 ;}// create a separate thread iRetVal = pthread_create (& SingleHandle, NULL, (void * (*) (void *) (& ProcessTask ), NULL); if (0! = IRetVal) {printf (Create ProcessTask failed !); Return-1;} return 0 ;} /*************************************** * ******************************** function description: scan thread * input parameter: pParam-thread Number * output parameter: none * return value: none * Other description: no * modified date version number modifier modified content * found * 20151029 V1.0 Zhou Zhaoxiong create *********************** **************************************** * *******/void ScanTask (void * pParam) {UINT32 iThreadNo = 0; // thread number iThreadNo = (UINT32) pParam; // obtain the thread number printf (Now, into ScanTask [% d]., iThreadNo ); // print the message containing the thread number // perform subsequent operations }/************************* **************************************** * ***** function description: processing thread * input parameter: none * output parameter: none * return value: none * Other description: no * modified date version number modifier modified content * found * 20151029 V1.0 Zhou Zhaoxiong create *********************** **************************************** * *******/void ProcessTask (void * pParam) {printf (Now, into ProcessTask .); // perform subsequent operations}
    
   
  

Description:
First, this program uses the pthread_create function to create a thread. The prototype of this function is:

Int pthread_create (pthread_tTidp, const pthread_attr_t * attr, (void)(Start_rtn) (void), Void * arg );

The first parameter is the pointer to the thread identifier, Which is MultiHandle and SingleHandle in this program.
The second parameter is used to set the thread attributes.
The third parameter is the starting address of the thread-running function. In this program, it is the function name.
The fourth parameter is the parameter used to run the function. When multiple threads with the same function are created at the same time, this parameter indicates the thread number.

Second, in Linux, the program compilation command is gcc-g-o ThreadCreate. c-lpthread. Note that the last "-lpthread" cannot be omitted, otherwise the program compilation fails. Because pthread is not the default library in Linux, to use it as a library in Linux, you need to add "-lpthread" or "-pthread" to explicitly link the library.
Third, it is recommended that you do not add or subtract the same global variable at the same time in the multi-thread of the program. If you do need to do so, be sure to use the lock operation in key code.

Summary
With the enhancement of software functions, the increasing complexity of the program also makes the transformation of the program from "single thread" to "multi-thread" inevitable.
"Multithreading" and "single thread" correspond to "Parallel" and "serial" respectively, which are a programming method that software developers must master. A well-designed multi-thread program not only has clear logic and is easy to read, but also has high execution efficiency, which is of great significance for improving the efficiency and quality of software products.
Finally, we recommend that you read an article "a simple explanation of process and thread" (http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html), this article shows the difference between process and thread in a graphical way, and other concepts related to the operating system are worth reading.

 

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.