Introduction to "multithreading" and its C code implementation framework

Source: Internet
Author: User

In some books related to computer science, we often hear the concept of "multithreading". So what is "multithreading"? When do I use "multithreading"? What are the benefits of using "multithreading" in programming? Many of the first-time programmers are also very curious about "multithreading", that it is "big on". In this paper, "Multithreading" is briefly introduced, and the implementation framework of its C code is given.

"single-threaded" programs
To understand the "multi-threaded", then you have to start with the "single thread".
We all know the factory "assembly line" operations, the process is tied up, only the previous process is completed before the next process can be started. This is actually very similar to the principle of "single thread".
In the "single thread", the function of the program is executed sequentially, only the previous process is executed successfully, the subsequent process can be executed to. For example, to implement a single-word file generation, upload, and delete program, using a "single-threaded" program to complete, then its process 1 is shown.

Figure 1 "Single thread" program

"multithreaded" programs
As you may notice, the process of generating files, uploading files, and deleting files in Figure 1 can actually be separated. In other words, these three processes are not affected by each other. This is also the birth of the concept of "multithreading".
"Multithreading", as the name implies, is multiple "single-threaded", each thread to complete the relevant functions independently. The program shown in 1, if implemented with "multithreading", is shown in Process 2.

Figure 2 "Multithreaded" program

As you can see from Figure 2, when the program starts, thread 1, thread 2, and thread 3 are running at the same time. Thread 1 is only used to generate the Word file, thread 2 is used only on the Messenger single file, thread 3 is only used to delete the expired single file. In this way, the success of any one thread does not affect the other two threads, really implemented the "parallel" program.

Advantages of "multithreading"
"Multithreading" in large-scale software programs have a wide range of applications, the advantages are as follows:
First, the original in a large process implemented in a number of small processes, 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.
Thirdly, "multithreading" makes the program more modular, which is helpful for tracking program execution process and troubleshooting problems.

"Multithreaded" C-code framework

/*********************************************************************** All rights reserved (C), Zhou Zhaoxiong.** File name: threadcreate.c* File ID: None* Content Summary: Demonstrating the creation of multithreading* Other instructions: None* Current version: V1.0* Author: Zhou Zhaoxiong* Completion Date: 20151029***********************************************************************/#include <stdio.h>#include <stdlib.h>#include <pthread.h>Redefine data type typedef signed INT int32;typedef unsigned int uint32;//macro definition#define THREAD_NUM 5//Number of threadsfunction declaration void Scantask (void *pparam); void Processtask (void *pparam);*********************************************************************** Function Description: main function* Input parameters: None* Output parameters: None* return value: None* Other instructions: None* Modified Date version number modify the content of the person* -------------------------------------------------------------------* 20151029 V1.0 Zhou Zhaoxiong created***********************************************************************/int32 Main () {pthread_t multihandle = 0; Multi-threaded handlepthread_t singlehandle = 0; Single Thread handleUINT32 iloopflag = 0;INT32 iretval = 0; To create a return value for a thread function//Loop Create threadFor (iloopflag = 0; Iloopflag < Thread_num; Iloopflag + +)    {iretval = pthread_create (&multihandle, NULL, (void * (*) (void *)) (&scantask), (void *) iloopflag); if (0! = iretval)        {printf ("Create scantask%d failed!\n", iloopflag);return-1;        }    }//Create threads individuallyiretval = pthread_create (&singlehandle, NULL, (void * (*) (void *)) (&processtask), null);if (0! = iretval)    {printf ("Create processtask failed!\n");return-1;    }return 0; }/*********************************************************************** Function Description: Scan thread * input parameter: pparam-thread number * OUTPUT parameter: no * return value: None * Other instructions: no * Modified date version number modified by the person *---- ------------------------------------------------------------------*  20151029 V1.0 Zhou Zhaoxiong created************************************************************************/void scantask (void *pparam) {UINT32 ithreadno = 0; Thread NumberIthreadno = (UINT32) pparam; Get Thread numberprintf ("Now, into scantask[%d].\n", ithreadno); Print a message that contains a thread number//Perform subsequent operations}/*********************************************************************** Function Description: Processing thread * Input parameters: None * Output parameters: None * return value: None * Other instructions: no * Modified date version number modified by the content of the changes *-------------- --------------------------------------------------------*  20151029 V1.0 Zhou Zhaoxiong created************************************************************************/void processtask (void *pparam) {printf ("Now, into processtask.\n");//Perform subsequent operations}

Description :
First, the program uses the Pthread_create function to create a thread, and the prototype of the function is:

int pthread_create (pthread_t tidp,const pthread_attr_t *attr, (void) (start_rtn) (void), void *arg);

The first parameter is a pointer to the thread identifier, which is Multihandle and Singlehandle in this program.
The second parameter is used to set the thread properties.
The third parameter is the starting address of the thread's running function, which is the function name in this program.
The fourth parameter is the parameter that runs the function, which represents the thread number when multiple threads of the same function are created simultaneously.

Second, under Linux, the compiler command for the program is: Gcc-g-o threadcreate threadcreate.c–lpthread. Note that the last "–lpthread" cannot be omitted, otherwise the program compiles without passing. Because Pthread is not the default library for Linux systems, and you want to use it as a library in Linux, you need to add "-lpthread" or "-pthread" to explicitly link the library.
Thirdly, in the multi-threading of the program, it is recommended not to add or subtract the same global variable at the same time. If you do need to do this, be aware of using the lock operation at the critical code.

Summary
With the enhancement of the software function, it is the increase of the program complexity, which makes the program from "single-threaded" to "multi-thread" become inevitable.
"Multithreading" and "single thread" correspond to "parallel" and "serial" respectively, which is a kind of programming method that software developers must master. The design of a reasonable "multithreading" program is not only logical clear, easy to read, and the execution of the program is high efficiency, for the SOFTWARE product efficiency and quality improvement has very important significance.
Finally, we recommend that you read an article "a simple explanation of processes and threads" (http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html), This article graphically shows the difference between a process and a thread, and other concepts about the operating system that are worth reading.

Original link: HTTP://WWW.DAXIXIONG.COM/?/ARTICLE/12

The code in this article has been submitted to GitHub, see: Https://github.com/zhouzxi/ThreadCreate

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to "multithreading" and its C code implementation framework

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.