Basics of Multithreaded programming

Source: Internet
Author: User
Tags function prototype terminates

First, the thread concept

1. Introduction

We know that the process runs in its own separate address space, that sharing data between processes requires a mmap or interprocess communication mechanism, and this article will learn how to execute multiple threads in the address space of a process. Some situations need to execute multiple control processes simultaneously in a process, when the thread comes into use, such as to implement a graphical interface of the download software, on the one hand need to interact with the user, waiting for and processing the user's mouse keyboard events, on the other hand need to download multiple files simultaneously, waiting and processing from multiple network hosts sent data , these tasks require a "wait-and-process" loop, which can be implemented in multiple threads, one thread is dedicated to interacting with the user, and the other thread is responsible for communicating with a network host.

2, what is called the thread

Multiple lines of execution in a program are called threads. A more accurate definition is that a thread is " a control sequence inside a process ". A typical UNIX process can be seen as having only one control thread: a process that only does one thing at a time. With multiple control threads, the process can be programmed to do more than one thing at a time, with each thread handling separate tasks. Threads can be thought of as lightweight processes, which are the basic unit of operating system scheduling. The main function and signal processing function is the same process in the address space of multiple control processes, multithreading is the same, but more flexible than the signal processing function, signal processing functions of the control process is only in the signal recursion, after processing the signal is finished, and multithreading control process can coexist for a long time, The operating system schedules and switches between threads as if it were scheduled and toggled between multiple processes.

3. Threading Features

Multiple threads of the same process share the same address space. Where text Segment, Data Segment are shared, if you define a function that can be called in each thread, if you define a global variable that can be accessed in each thread, in addition, the threads share the following process resources and environment: (1) Line part descriptor ; (2) Processing of each signal (sig_ign, SIG_DFL or custom signal processing function), (3) Current working directory, (4) User ID and group ID. However, some resources are unique to each thread: (1) thread ID, (2) context, including the values of various registers, program counters and stack pointers, (3) stack space, (4) errno variables, (5) signal shielding words, (6) Scheduling priority.

4. Advantages and disadvantages of threading

Advantages: (1) The Code that processes asynchronous time can be simplified by assigning separate threads to the processing of each event type;
(2) Multiple threads can automatically share the same storage address space and file descriptors;
(3) Some problems can be decomposed to improve the overall throughput of the program;
(4) The interactive program can realize the improvement of the corresponding time by using multithreading, and multithreading can separate the part of the program from the other parts of the user input and output.

Cons: Threads also have shortcomings. Writing multithreaded programs requires a more holistic and deeper thinking. In a multithreaded session, there is a great chance that the subtle deviations in time allocation or the sharing of variables that should not be shared have an adverse effect. Debugging a multithreaded thread is much more difficult than debugging a single-threaded one.

Second, the Line program control system

1. Creation of threads

Name: Pthread_create
Features: Creating Threads
Header files: #include <pthread.h>
Function prototype: int pthread_create (pthread_t *thread,const pthread _attr_t *attr,void * (*start_routine) (void*), void *restrict arg );
Parameters: The first parameter, thread, refers to the ID
Return value: Returns 0 if successful return, otherwise returns the error number

When Pthread_creat successfully returns, the memory unit that TIDP points to is set to the thread ID of the newly created thread. The attr parameter is used to customize various thread properties. You can set it to NULL to create a default thread property. The newly created thread runs from the address of the START_RTN function, which has only an untyped pointer parameter arg, and if more than one parameter is required to pass to the START_RTN function, then these parameters need to be placed in a struct, and the address of the structure is passed in as the arg parameter.

we have to add a parameter to the compilation of the process –lpthread otherwise we are not prompted to find the error of the function .
The specific compilation method is Gcc–lpthread–o pthread PTHREAD.C
Run the result as

Previously learned system functions are successfully returned 0, failed to return 1, the error number is saved in the global variable errno, and the function of the Pthread library is returned by the return value of the error number, although each thread also has a errno, but this is to be compatible with other function interfaces, The Pthread library itself does not use it and returns the error code with a clearer return value.
After calling Pthread_create () in a thread to create a new thread, the current thread returns from Pthread_create () to continue execution, and the code executed by the new thread is passed to the Pthread_create function pointer Start_ Routine decided. The Start_routine function receives multiple parameters, which are passed to it by the arg parameter of Pthread_create, which is of type void *, and the pointer is defined by what type of the caller. The return value type of start_routine is also void *, and the meaning of this pointer is also defined by the caller itself. When Start_routine returns, the thread exits, and other threads can call Pthread_join to get the return value of Start_routine, similar to the parent process calling wait (2) to get the child process exit state, followed by a detailed description Pthread_ Join

3, Name: pthread_self
Function: Gets the ID of its own thread
Header files: #include <pthread.h>
Function prototype: pthread_t pthread_self (void);
Parameters: None
Return value: Thread ID of the calling thread

This function is already used in the example above.

3, the termination of the thread

Threads exist by process, and when the process terminates, the thread terminates. Of course there is a control flow that stops the entire process without terminating it.
1) return from the thread function. This method does not apply to the main thread, and return from the main function is equivalent to calling exit.
2) One thread can call Pthread_cancel to terminate another thread in the same process.
3) The thread can call Pthread_exit to terminate itself. Terminating a thread with Pthread_cancel synchronization and asynchronous two cases, more complex, and later detailed introduction.

(1) Name: Pthread_exit
Function: Terminates a thread
Header files: #include <pthread.h>
Function prototype: void Pthread_exit (void *rval_ptr);
Parameter: RVAL_PRT is an untyped pointer similar to a single parameter passed to the start routine. Other threads in the process can call the Pthread_join function to access this pointer.
return value: None

RetVal is a void * type, and the use of a thread function return value is the same as other threads can call Pthread_join to get this pointer. It is important to note that the Pthread_exit or return pointer points to a memory cell that must be global or malloc allocated and cannot be allocated on the stack of the thread function, because when the other thread gets the return pointer, the function has exited.

(2) Thread wait

Name: Pthread_join
Function: The thread that called the function suspends the wait until a thread with the ID of thread terminates.
Header files: #include <pthread.h>
Function prototype: int pthread_join (pthread_t thread,void **rval_ptr);
Parameters:
Return value: Returns the error number if 0 is returned successfully.

Thread threads terminate in different ways, and the terminating state obtained through Pthread_join is different, summarized as follows:
1. If the thread thread returns through return, the cell that value_ptr points to is the return value of the thread's function.
2. If the thread thread is called by another thread, the pthread_cancel exception ends, and value_ptr points to the cell where the constant pthread_canceled is stored.
3. If thread threads are terminated by their own invocation of pthread_exit, the cell to which value_ptr points is stored is a parameter passed to Pthread_exit. If you are not interested in the terminating state of thread threads, you can pass NULL to the VALUE_PTR parameter.
When a thread exits by calling Pthread_exit or simply returns from the boot journey, other threads in the process can get the process's exit state by calling the Pthread_join function . The call to the Pthread_join process will remain blocked until the specified thread calls Pthread_exit, either from the startup routine or canceled.
If the thread only returns from its startup journey, Rval_ptr will contain the return code.

The output results are as follows:

The value of the constant pthread_canceled in the Linux pthread Library is 1. You can find its definition in the header file pthread.h.
In general, after a thread terminates, its terminating state is retained until the other thread calls Pthread_join to get its state. But the thread can also be set to the detach state, so that once the thread terminates, it reclaims all the resources it occupies without leaving the terminating state. You cannot call Pthread_join on a thread that is already in the detach state, and such a call will return EINVAL. Calling Pthread_join or Pthread_detach on a thread that has not yet been detach can set the thread to the detach state, which means that you cannot call two pthread_join on the same thread. Or, if you have already called Pthread_detach on a thread, you can no longer call pthread_join. Return value: Successful return 0, Failure returns error number.




Basics of Multithreaded programming

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.