Analysis and Implementation of multithreading mechanism in Linux

Source: Internet
Author: User
Linux Analysis and Implementation of The multithreading mechanism underLiu jingquan 1 Wang Xian 1 Zhou weiyun 2 (1 School of Communication and control engineering, Jiangnan University 2 Wuxi Meath Technology Co., Ltd., Wuxi 214122, China) SummaryThis paper introduces the basic concepts of Linux threads, the mutex and synchronization mechanisms between threads, analyzes the API functions of the linuxpthread library, and illustrates the core technology of multi-thread programming in combination with an example, finally, the precautions for multithreading programming are summarized. KeywordsThread process synchronization mutex 1 . IntroductionCurrently, many popular multi-task operating systems provide the thread mechanism. A thread is a single sequential control flow in a program. Multi-threaded program design is to divide a program (process) task into multiple parts (threads) for execution, and each thread is an ordered single control flow, all threads are executed concurrently. In this way, multi-threaded programs can implement parallel computing and efficiently utilize multi-processor. Threads can be divided into user-level threads and kernel-level threads. User-level threads do not require Kernel support and can be implemented in user programs. Thread Scheduling, synchronization, and mutex must be completed by the user program. Kernel-level threads require kernel participation. The kernel completes Thread Scheduling and provides corresponding system calls. User Programs can use these interface functions to control and manage threads. The Linux operating system provides the linuxthreads library, which is a kernel-level multi-thread function library compliant with posix1003.1c standards. The linuxthreads Library provides some key functions for multi-threaded programming, including pthread. H files. 2. linuxthread Key library functions in2.1 create and terminate an int pthread_create (pthread_t * pthread, const pthread_attr_t * ATTR, void * (* start_routine (* void), void * Arg ); you can call this function to create a new thread and execute the program specified by start_routine after the new thread is created. The ATTR parameter is the attribute of the thread to be created. If it is null, it indicates that the thread is created with the default attribute. Arg is a parameter passed to start_routine. When a new thread is successfully created, the system automatically allocates a thread ID for the new thread and returns it to the caller through pthread. Void pthread_exit (void * value_ptr); call this function to exit the thread. The value_ptr parameter is a pointer to the returned status value. 2.2 thread control function pthread_self (void () obtain your own thread ID. Int pthread_join (pthread-T thread, void ** status); this function is used to wait for the end of a thread. The thread that calls pthread_join () will be suspended until the thread ID specified by the thread parameter is terminated. Int pthread_detach (pthread_t pthread); The pthread parameter indicates that once the thread is terminated, all resources occupied by the thread are released immediately. 2.3 The mutex between threads is similar to that in the critical section. Only threads with mutex have the permission to access resources. Because there is only one mutex object, this determines that the shared resource (code or variable) will not be accessed by multiple threads at the same time under any circumstances. Mutual exclusion can be used not only to securely share resources in different threads of the same application, but also to securely share resources between threads of different applications. In Linux, pthread_mutex_t is used to define the mutex mechanism to complete the mutex operation. The specific operation functions are as follows: pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * ATTR); A mutex variable is first made. The ATTR parameter indicates creating mutex Based on the ATTR attribute, if the ATTR parameter is null, it is created by default. Pthread_mutex_lock (pthread_mutex_t * mutex); lock a mutex variable. If the mutex specified mutex has been locked, the calling thread will be blocked until the mutex thread has been unlocked. Pthread_mutex_unlock (pthread_mutex_t * mutex); unlock the mutex variable specified by mutex. 2.4 synchronization between threads means that the thread waits for an event. When a waiting event occurs, the waiting thread and the event will continue to be executed together. If the waiting event does not arrive, it is suspended. In Linux, conditional variables are used for synchronization. Pthread_cond_init (pthread_cond_t * cond, const pthread_cond_t * ATTR); this function converts a condition variable cond according to the attributes specified by ATTR. Pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex); wait for an event (condition variable) to happen, and the calling thread will automatically block until the corresponding condition variable is set to 1. Threads in the waiting state do not occupy CPU time. Pthread_cond_signal (pthread_cond_t * Cond); Removes the blocking status of a thread waiting for the condition variable specified by the cond parameter. 3 . Multi-threaded programming application example.Here, multithreading technology is used to implement producer and consumer problems. The producer thread writes data to a buffer zone and the consumer thread reads data from the buffer zone. Because the producer thread and consumer thread share the same buffer zone, to read and write data correctly, the Buffer Queue must be mutually exclusive. The producer thread and consumer thread must satisfy the following requirements: the number of buffer written by the producer cannot exceed the buffer capacity, and the number of read by the consumer cannot exceed the number of write by the producer. A small trick is used in the program to determine whether the buffer is empty or full. During initialization, the read pointer and write pointer are 0. If the read pointer is equal to the write pointer, the buffer is empty. If (write pointer + 1) % N is equal to the read pointer, the buffer is full. % indicates taking the remainder. In this case, a unit is actually empty and unused. The following are complete program sections and comments. # Include <stdio. h>
#include<pthread.h>
#define BUFFER_SIZE 8
Struct prodcons {// buffer-related data structure int buffer [buffer_size]; // array of actual data storage pthread_mutex_t lock; // mutex lock, used for mutex operation on the buffer zone int readpos, writepos; // read/write pointer pthread_cond_t notempty; // condition variable pthread_cond_t notfull, which is not empty in the buffer zone; // condition variable that is not full in the buffer zone }; /* initialize the Buffer Structure */void Init (struct prodcons * B) {pthread_mutex_init (& B-> lock, null); pthread_cond_init (& B-> notempty, null ); pthread_cond_init (& B-> notfull, null); B-> readpos = 0; B-> writepos = 0;}/* put the product into the buffer zone. Here Is to save an integer */void put (struct prodcons * B, int data) {pthread_mutex_lock (& B-> lock ); /* Wait for the buffer to be below */If (B-> writepos + 1) % buffer_size = B-> readpos) {pthread_cond_wait (& B-> notfull, & B-> lock);}/* write data and move the pointer */B-> buffer [B-> writepos] = data; B-> writepos ++; if (B-> writepos> = buffer_size) B-> writepos = 0;/* set the condition variable not empty in the buffer */pthread_cond_signal (& B-> notempty ); pthread_mutex_unlock (& B-> lock);}/* retrieve an integer from the buffer */INT get (struct prodcons * B) {int da Ta; pthread_mutex_lock (& B-> lock);/* Wait for the buffer to be non-empty */If (B-> writepos = B-> readpos) {pthread_cond _ Wait (& B-> notempty, & B-> lock);}/* read data, move the read pointer */Data = B-> buffer [B-> readpos]; B-> readpos ++; If (B-> readpos> = buffer_size) b-> readpos = 0;/* set the condition variable */pthread_cond_signal (& B-> notfull); pthread_mutex_unlock (& B-> lock); return data ;} # define over (-1) struct prodcons buffer; void * producer (void * Data) {int N; For (n = 0; n <10000; n ++) {print F ("% d/N", n); Put (& buffer, n);} Put (& buffer, over); return NULL ;} void * Consumer (void * Data) {int D; while (1) {d = get (& buffer); If (D = over) break; printf ("% d/N", d);} return NULL;} int main (void) {pthread_t th_a, th_ B; void * retval; Init (& buffer ); /* Create producer and consumer threads */pthread_create (& th_a, null, producer, 0); pthread_create (& th_ B, null, consumer, 0 ); /* wait for two threads to end */pthread_join (th_a, & retval); pthread_join (th_ B, & retval); Return 0 ;} In the preceding example, the producer writes integers from 1 to 1000 to the buffer, while the consumer reads and prints the written integers from the same buffer. Because the producer and consumer are two threads running at the same time and must use the same buffer for data exchange, a mechanism must be used for synchronization. Through the above example, we can see that the biggest advantage of Multithreading is that almost all data except the stack is shared, so inter-thread communication efficiency is very high; disadvantages: because all data is shared, it is very easy to cause data corruption between threads. This must be noted during programming. 4. ConclusionIn Linux, the POSIX-based multi-thread technology is well supported, which reduces the system overhead During Concurrent execution of programs and improves the working efficiency of computers. In the specific programming process, we should understand the relationship between threads, and also consider the protection of shared data to ensure efficient code operation under the mutex and synchronization mechanisms, use gcc-D-reentrant-libpthread during program compilation. XX. so filename. c compilation. 5. References[1] Zheng yanfei, Yu Haiyan. discussion and Practice of multi-thread mechanism in Linux [J]. computer Applications, 2001. [2] Liu Yu. LINUX multi-thread mutex and synchronization control and practices [J]. journal of Anhui metallurgical Science and Technology Vocational College, 2005. [3] Yao jifeng. linux application examples and tips [M]. beijing: Machinery Industry Press. 2001 [4] Wei Yongming. linux practical tutorial [M]. beijing: Electronics Industry Press, 2000. [5] Tang Jing. advanced Programming Guide for C language on UNIX platforms [M]. beijing: Hope electronics Publishing House, 2000.

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.