1. Thread Concept: Threads and processes have certain similarities, often called lightweight processes, where multiple threads in the same process willshare all of the system resources in the process, such as virtual address space, file descriptors, signal processing, and so on。 But multiple threads in the same processAllhave self-controlsystemFlow
(its own instruction counter and CPU clock) and the respective call stack (called stack), its own register environment (register context), its own thread local storage (thread-local storage). A process can have many threads, and each thread performs different tasks in parallel.
Threads can improve the performance of applications that handle blocking situations such as file I/O or socket I/O in multicore environments. In UNIX systems, a process contains many things, including executable programs and a whole host of resources such as the file descriptor address space. In many cases, there is a need to exchange data between different code that completes the related task. If the multi-process approach, then the communication needs in the user space and kernel space for frequent switching, the overhead is very large. However, if you use multithreading, because you can use shared global variables, communication between threads (data exchange) becomes very efficient and clearly represents the difference between a process and a thread in resources and control flow
According to the textbook definition, a process is the smallest unit of resource management, and a thread is the smallest unit of program execution. In the design of the operating system, from the process evolution of the thread, the main purpose is to better support SMP and reduce (process/thread) context switching overhead.
Regardless of the division, a process requires at least one thread as its instruction executor, and the process manages resources (such as CPUs, memory, files, and so on), while assigning threads to a CPU to execute. A process can of course have multiple threads, at this point, if the process runs on an SMP machine, it can use multiple CPUs at the same time to execute each thread, to achieve maximum parallelism to improve efficiency, and even on a single CPU machine, the use of multithreaded models to design programs, As in the case of a multi-process model in lieu of a single process model, the design is more concise, more complete, more efficient execution of the program, such as the use of multiple threads to respond to multiple inputs, the multi-threaded model implementation of the function can actually be implemented with a multi-process model, compared with the latter, The context switching overhead of a thread is much smaller than the process, and semantically, in response to multiple input functions, it is actually sharing all resources except the CPU.
A thread's function call generally succeeds in returning 0, and the failure returns non 02. Operation of the thread Main three issues: thread's creation thread's terminating thread's synchronous mutex(1) Creation of threadsIf your Linux does not have a thread-related man document, install the online man help:
sudo Install manpages-posix Manpages-posix-dev
#include <pthread.h> intconst pthread_attr_t *attr, void * (* Start_routine) (voidvoid *// four parameter meaning pthread_t *Thread: *-pthread.
(2). Termination of ThreadThe original version of the Linux man document is very clear.
The new thread terminates (terminated)inchOne of the following ways:* It CallsPthread_exit (3 ), specifying (specified) an Exit status value, available to another threadinchThe same process that calls Pthread_join ( 3). *It returns from Start_routine (). This is equivalent (equivalent) to calling Pthread_exit ( 3)With the value suppliedinchThe return statement. * It is canceled (seePthread_cancel (3)). * Any of the threadsinchThe Process calls exit (3), or the main thread performs a return from main (). This causes the termination of all threadsinchThe process.
There are three ways to terminate a thread without terminating the entire process: 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. One thread can call Pthread_cancel to terminate another thread in the same process. A thread can call Pthread_exit to terminate itself.(3). Properties of a thread (second parameter to create a process)TheattrArgument points to a pthread_attr_t structure whose contents is used at thread creation time to determine attr Ibutes for the new thread; This structure is initialized usingPthread_attr_init (3)and related functions.If attr isNULL, then the thread was created withdefault attributes.Sets the detach attribute of the thread (1). pthread_attr_t attr; Pthread_attr_init (&ATTR); Pthread_attr_setdetachstate (&attr,pthread_create_detached); (2). Pthread_detach (Pthread_self ())(4) Mutual exclusion lock for thread
Because threads share the resources and address space of a process, the synchronization and mutex of resource access between threads must be taken into account when manipulating these resources
There are two mechanisms: mutexes and semaphores, which apply to the case where the available resources are unique, and the semaphore is applied to multiple instances of available resources
The basic function of the mutex:
1, Pthread_mutex_init (): Mutex initialization
2. Pthread_mutex_lock (): Mutex lock
3, Pthread_mutex_trylock (): Mutual exclusion Lock determination lock
The Pthread_mutex_trylock () call returns immediately when the mutex object specified by the parameter mutex is currently locked, in addition to Pthread_mutex_trylock () and Pthread_mutex_lock () Functions exactly the same.
4. Pthread_mutex_unlock (): Mutex lock unlock
5, Pthread_mutex_destory (): Elimination of mutual exclusion lock
- Initialize the lock to unlock state in the main thread
- pthread_mutex_t Mutex;
- Pthread_mutex_init (&mutex, NULL);
- Initialize lock to unlock state at compile time
- Lock initialization pthread_mutex_t mutex = Pthread_mutex_initializer;
- Lock operation and unlock operation when accessing an object
- Locking Pthread_mutex_lock (&mutex)
- Release lock Pthread_mutex_unlock (&mutex)
-
Lock protection is not our shared variable (or shared memory), for shared memory, the user cannot directly protect it, because that is the physical memory, can not prevent the code access of other programs. In fact, the lock is protecting critical areas, in this case, because all threads follow a rule, which is to enter the key area of the money 同一把 lock, in the exit key area money release 同一把 lock
#include <stdio.h>#include<stdlib.h>#include<pthread.h>intSharedi =0;voidIncrese_num (void);p thread_mutex_t Mutex=Pthread_mutex_initializer;intMain () {intret; pthread_t Thrd1, Thrd2, Thrd3; RET= Pthread_create (&thrd1, NULL, (void*) Increse_num, NULL); RET= Pthread_create (&thrd2, NULL, (void*) Increse_num, NULL); RET= Pthread_create (&thrd3, NULL, (void*) Increse_num, NULL); Pthread_join (Thrd1, NULL); Pthread_join (Thrd2, NULL); Pthread_join (Thrd3, NULL); printf ("Sharedi =%d\n", Sharedi); return 0;}voidIncrese_num (void) { Longi,tmp; for(i=0; i<=100000; i++) { /*Locking*/ if(Pthread_mutex_lock (&mutex)! =0) {perror ("Pthread_mutex_lock"); Exit (Exit_failure); } tmp=Sharedi; TMP= tmp +1; Sharedi=tmp; /*Ching*/ if(Pthread_mutex_unlock (&mutex)! =0) {perror ("Pthread_mutex_unlock"); Exit (Exit_failure); } }}==================== a problem with a mutex from advanced UNIX programming is probably that the call to unlock function Pthread_mutex_unlock (&mutex) fails, which causes the thread to exit. The mutex is locked. The workaround is to use a function to write the unlock and lock process to a function to encapsulate, and then the thread invokes the function to invoke the encapsulated function. The semaphore is transferred from someone else, and the link is given below(5). Thread Semaphore
The lock has a very obvious drawback, and that is it 只有两种状态 : locking and not locking.
The semaphore is essentially a non-negative integer counter that is also used to control access to public resources. When the public resources increase, call the semaphore increment function sem_post () to increase it, and when the public resources are reduced, call the function sem_wait () to reduce the semaphore. In fact, we can treat the lock as a 0-1 semaphore.
They are /usr/include/semaphore.h defined in, the semaphore data structure is sem_t, essentially, it is a long integer
Related functions
Before using semaphore, we need to first introduce the header file#include <semaphore.h>
- To initialize the semaphore:
int sem_init(sem_t *sem, int pshared, unsigned int value);
- Successful return 0, failure return-1
- Parameters
- SEM: A pointer to a semaphore structure
- Pshared: When not 0, the semaphore is shared between processes, otherwise it can only be shared for all threads of the current process
- Value: The initial value of the semaphore
- The signal volume minus 1 operation, when sem=0 the function will block
int sem_wait(sem_t *sem);
- Successful return 0, failure return-1
- Parameters
- SEM: A pointer to the semaphore
- Signal Volume plus 1 operation
int sem_post(sem_t *sem);
- Parameter and return as above
- Destroy Signal Volume
int sem_destroy(sem_t *sem);
- Parameter and return as above
-
/************************************************************************* > File name:sem.c > Author:coul DTT (fyby) > Mail: [email protected] > Created time:2013 December 15 Sunday 19:25 08 seconds ******************************* *****************************************/#include<stdio.h>#include<unistd.h>#include<pthread.h>#include<semaphore.h>#defineMAXSIZE 10intStack[maxsize];intSize =0; sem_t sem;//producersvoidProvide_data (void) { inti; for(i=0; i< MAXSIZE; i++) {Stack[i]=i; Sem_post (&SEM);//add 1 to the signal volume }}//ConsumervoidHandle_data (void) { inti; while((i = size++) <MAXSIZE) {sem_wait (&SEM); printf ("multiplication:%d X%d =%d\n", Stack[i], stack[i], stack[i]*Stack[i]); Sleep (1); }}intMainvoid) {pthread_t provider, handler; Sem_init (&sem,0,0);//initialization of signal volumePthread_create (&provider, NULL, (void*) Handle_data, NULL); Pthread_create (&handler, NULL, (void*) Provide_data, NULL); Pthread_join (provider, NULL); Pthread_join (handler, NULL); Sem_destroy (&SEM);//Destroy signal Volume return 0;}
- System calls to Threads 1.pthread_createname pthread_create-create a new threadsynopsis #include <pthread.h> int Pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*start_routine) (void *), VO ID *arg); Compile and Link with-pthread.2.pthread_exit (3) 3.pthread_join (3) 4.pthread_cancel (3) 5.pthread_attr_init (3)// Property initialization function #include <pthread.h> int pthread_attr_init (pthread_attr_t *attr); int Pthread_attr_destroy (pthread_attr_t *attr); Compile and Link With-pthread.6.pthread_detach ()//Set Thread Detach property 7.pthread_self ()
Reference: "1" http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html "2" http://www.cnblogs.com/fuyunbiyi/p /3475602.html "3", "Advanced UNIX Programming" Linux threading Implementation Mechanism: https://www.ibm.com/developerworks/cn/linux/kernel/l-thread/
Linux Threading Programming