Thread learning notes

Source: Internet
Author: User
Tags semaphore
Process is in the system Program Basic Unit of execution and resource allocation. Each process has its own data segment, Code Segment and stack segment, which causes the process to have more responsible context switches and other actions during switchover and other operations.

Thread: it is a basic scheduling unit in a process, and has a series of registers independent of the program counter stack.

Threads can be divided into user-level threads and core-level threads according to their schedulers. A user-level thread can correspond to one or several core-level threads, that is, one-to-one or multiple-to-one models.

1. Create thread
Pthread_t a_thread; // Save the thread variable
Pthread_attr_t a_thread_attribute; // thread attributes
Void thread_function (void * argument); // function used during thread execution
Char * some_augument; // function parameter

Pthread_create (& a_thread, a_thread_attribute, (void *) & thread_function, (void *) some_augument );
The thread attribute only specifies the minimum size of the stack to be used. In future programs, other values can be specified for thread attributes, but most programs can use the default values.

# Include <stdio. h>
# Include <pthread. h>
Void print_message_function (void * PTR)
{
Char * message;
Message = (char *) PTR;
Printf ("% s", message );
}

Int main ()
{
Pthread_t pthread1, pthread2;
Char * message1 = "hello ";
Char * message2 = "world ";
Pthread_create (& pthread1, null, (void *) & print_message_function, (void *) message1 );
Pthread_create (& pthread2, null, (void *) & print_message_function, (void *) message2 );
Return 0;
}
Gcc-O pthread. C-l pthread

When the parent process ends, all child threads end.
All other threads will be terminated when exit is called by any thread (no matter the parent thread or sub-thread. If you want the threads to terminate separately, you can use the pthread_exit function.

When the thread calls s l e p, the whole process is in sleep state, that is, all three threads are in sleep state.

The function to sleep a thread is pthread_delay_np. For example, to sleep a thread for 2 seconds, use the following program:
Struct timespec delay;
Delay. TV _sec = 2;
Delay. TV _nsec = 0;
Pthread_delay_np (& delay );

Void pthread_exit (void * retval );
Retval: the return value of the pthread_exit () call thread, which can be checked and obtained by other functions such as pthread_join.

2. modify attributes of a thread
Define attributes, separation attributes, stack address, stack size, priority
Default: Non-bound, non-separated, default im stack, same level as parent process priority.

Binding property:
In Linux, a user thread corresponds to a kernel thread. Binding attribute refers to a user thread allocated to a kernel thread, because the scheduling of CPU time slice is oriented to the kernel process.

Separation attributes:
Determines how a thread terminates itself.
Non-separation: When the thread ends, the system resources occupied are not released. Only when the pthread_join () function returns, the created thread can release its own system resources.

Pthread_attr_init
Pthread_attr_setscope // you can specify the binding property.
Pthread_attr_setdetachstate // sets the thread separation attribute.
Pthread_attr_getschedparam // gets the thread priority.
Pthread_attr_setschedparam // sets the thread priority.

Int pthread_attr_init (pthread_attr_r * ATTR)
ATTR: thread attributes

Int pthread_attr_setscope (pthread_attr_r * ATTR, int scope)
Scope: pthread_scope_system: bind
Pthread_scope_process: not bound

Int pthread_attr_setdetachstate (pthread_attr_r * ATTR, int detachstate)
Detachstate: pthread_create_detached: Separate
Pthread_create_joinable: Non-separated

Int pthread_attr_getschedparam (pthread_attr_t * ATTR, struct sched_param * PARAM)
Param: thread priority

Int pthread_attr_setschedparam (pthread_attr_t * ATTR, struct sched_param * PARAM)

3. thread control

POSIX provides two methods for thread synchronization: mutex and conditional variable.
Mutex is a simple locking method to control access to shared resources.

Int pthread_jon (pthread_t th, void ** thread_return );

Thread_return: a user-defined pointer used to store the return values of the waiting thread.

Pthread_join (pthread1, null );

A mutex thread control
Mutex is a simple locking method to control access to shared resources. The mutex lock has only two States: locking and unlocking. You can regard the mutex as a global variable in a sense.

The operations of mutex lock mainly include the following steps.
• Mutex lock initialization: pthread_mutex_init
• Mutex lock: pthread_mutex_lock
• Mutex lock: pthread_mutex_trylock
• Mutex lock unlock: pthread_mutex_unlock
• Remove mutex: pthread_mutex_destroy
A mutex can be divided into a quick mutex lock, a recursive mutex lock, and an error mutex lock. The major difference between these three locks is whether other threads that do not possess the mutex lock need to block the wait when they want to obtain the mutex lock. A quick lock means that the calling thread is blocked until the thread with the mutex lock is unlocked. Recursive mutex locks can be returned successfully and increase the number of times the call thread locks on the mutex. If an error occurs, the mutex lock is a non-blocking version of the quick mutex lock, it returns an error message immediately.

Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * mutexattr)
Mutexattr:
Pthread_mutex_initializer: Creates a fast mutex lock.
Pthread_recursive_mutex_initializer_np: Create recursive mutex lock
Pthread_errorcheck_mutex_initializer_np: Create an error mutex lock

Int pthread_mutex_lock (pthread_mutex_t * mutex ,)
Int pthread_mutex_trylock (pthread_mutex_t * mutex)
Int pthread_mutex_unlock (pthread_mutex_t * mutex ,)
Int pthread_mutex_destroy (pthread_mutex_t * mutex ,)

B semaphore thread control

PV operation P minus one V add one
Processes (or threads) determine whether to have access to public resources based on the semaphore value. When the semaphores SEM value is greater than or equal to zero, the process (or thread) has access to public resources; on the contrary, when the semaphores SEM value is less than zero, the process (or thread) it will be blocked until the semaphores SEM value is greater than or equal to 0.

The PV primitive is mainly used for synchronization and mutex between processes or threads. If used for mutex, several processes (or threads) usually set only one semaphore Sem. Their operation process is shown in 9.2. When semaphores are used for synchronization operations, multiple semaphores are often set and different initial values are arranged to implement sequential execution between them.

• Sem_init is used to create a semaphore and initialize its value.
• Sem_wait and sem_trywait are equivalent to P operations. Both of them can reduce the semaphore value by one. The difference between them is that if the semaphore is smaller than zero, sem_wait will block the process, and sem_trywait will return immediately.
• Sem_post is equivalent to the V operation. It adds the semaphore value and sends a signal to wake up the waiting process.
• Sem_getvalue is used to obtain the semaphore value.
• Sem_destroy is used to delete semaphores.

Int sem_init (sem_t * SEM, int pshared, unsigned int value)
SEM: semaphore
Pshared: determines whether the semaphore can be shared among several processes. Currently, Linux does not implement a shared semaphore between processes, so this value can only be 0.
Value: the initial semaphore value.

Int sem_wait (sem_t * SEM)
Int sem_trywait (sem_t * SEM)
Int sem_post (sem_t * SEM)
Int sem_getvalue (sem_t * SEM)

Int sem_destroy (sem_t * SEM)

POSIX thread, also known as pthread
1. What is thread?
Threads are concurrent multi-path execution paths in the shared memory space. They share the resources of a process, such as file descriptors and signal processing.
When switching between two common processes, it is costly for the kernel to switch from the context of one process to the context of another process, here, the main task of context switching is to save the CPU status of the old process and load the Save status of the new process, and replace the memory image of the old process with the memory image of the new process. The thread allows the process to switch between several running characters without performing the context switch mentioned above.

2_clone function call
# Include <sched. h>
Int _ clone (INT (* fN) (void * fnarg), void * child_stack, int flags, void * Arg );
_ Clone aims to make it easier to implement the pthread Library

Pthread_create function creation thread

(* FN) (void * fnarg) is a function pointer. This function is called when a sub-process is executed. fnarg is a parameter passed to FN.
Child_stack is the pointer to the stack that you just want to assign to your sub-process.
Arg is passed to the subfunction.

The returned value is the ID of the created sub-process.

Pthread Library
1. What is pthread?
Pthread is a standardized model used to divide a program into a group of tasks that can be executed simultaneously.
Pthread is a set of C function calls and data structures that implement POSIX thread standards, header files that provide interfaces <pthread. h>, and libpthread. O libraries that make calls take effect.

2 pthread_create Function
# Include <pthread. h>
Int pthread_create (pthread_t * thread, pthread_attr_t * ATTR, void * (* start_routime) (void *), void * Arg );
Thread: ID of the Core Thread
ATTR: determines which thread attribute is applied to the thread.
Pthread_attr_init: Set attributes of the new thread.
* Start_routime is a pointer to the function to be executed in the new thread.
Parameters passed by Arg to * start_routime.
0 is returned successfully, and the identifier of the new thread is saved in the thread.
Unlike fork () calling to create a process, the thread created by pthread_create () does not have the same execution sequence as the main thread (that is, the thread that calls pthread_create, instead, run the start_routine (ARG) function. The thread returns the ID of the created thread, while the ATTR is the thread attribute set when the thread is created (see below ). The return value of pthread_create () indicates whether the thread is successfully created. Although Arg is a void * type variable, it can also be passed to the start_routine () function as any type of parameter. At the same time, start_routine () can return a void * type return value, the returned value can also be of another type and is obtained by pthread_join.

Pthread_t is defined in the header file/usr/include/bits/pthreadtypes. h: typedef unsigned long int pthread_t;

2 pthread_exit Function
The pthread_exit function uses the pthread_cleanup_push function to call any clear handler for this thread, terminate the execution of the current thread, and return retval. Retval can be retrieved by the parent process or other processes through pthread_join.
# Include <pthread. h>
Void pthread_exit (void * retval );

3 pthread_join Function
Used to suspend the current process until the process to which th points is terminated.
The first parameter is the identifier of the waiting thread, and the second parameter is a user-defined pointer, which can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function called will wait until the end of the waiting thread. When the function returns, the resources of the waiting thread will be reclaimed. There are two ways to end a thread. One is that the function ends and the thread that calls it ends, as in the preceding example; another method is to use the pthread_exit function.
# Include <pthread. h>
Int pthread_join (pthread_t th, void ** thread_return );
Int pthread_detach (pthread_t th );

4 pthread_atfork Function
Three handler functions are registered and called when a new thread is created.
Int pthreadd_atfork (void (* prepare) (void), void (* parent) (void), void (* Child) (void ));

5. Cancel the thread
Int pthread_cancel (pthread_t thread );
Int pthread_setcancelstate (INT state, int * oldstate );
Int pthread_setcanceltype (INT type, int * oldtype );
Void pthread_testcancel (void );

A thread can use pthread_setcancelstate to set its cancellation state. This function has two parameters, satate is a new State, and oldstate is a variable pointer.
State:
Pthread_cancel_enable: allows the request to be canceled.
Pthread_cancel_disable ignore cancel request

Pthread_setcanceltype changes the method in which a thread cancels a request,
Type:
The pthread_cancel_asynchronous thread will be canceled immediately.
Pthread_cancel_deferred delays the cancellation thread until a cancellation point is reached.

Cancel point creation through pthread_testcancel

6 pthread cleanup macro
Registers a processing function routine. When pthread_exit is called to terminate the thread or the thread allows the cancellation of the request while reaching another cancellation point, it calls the processing function with a null pointer directed by Arg.

# Include <pthread. h>
Void pthread_cleanup_push (void (* routine), (void *), void * Arg );
Void pthread_cleanup_pop (INT execute );
Void pthread_cleanup_push_defer_np (void (* routine), (void *), void * Arg );
Void pthread_cleanup_pop_restore_np (INT execute );
When a processing function is pushed into a stack, pthread_cleanup_pop cancels the registration of the clearing processing function from the latest stack.

7. Create a binding process
# Include <pthread. h>
Pthread_attr_t ATTR;
Pthread_t tid;

/* Initialize the property value, which is set to the default value */
Pthread_attr_init (& ATTR );
Pthread_attr_setscope (& ATTR, pthread_scope_system );
The second parameter can be set to pthread_scope_system or pthread_scope_process.
Pthread_create (& tid, & ATTR, (void *) my_function, null );

The separation status of the 8-thread determines how a thread terminates itself. In the above example, we use the default attributes of the thread, that is, the non-separated state. The separation thread is not like this. It is not waiting by other threads. When the running ends, the thread is terminated and system resources are immediately released.
The function for setting the thread separation status is pthread_attr_setdetachstate (pthread_attr_t * ATTR, int detachstate ).
The second parameter can be pthread_create_detached (separated thread) and pthread _ create_joinable (non-separated thread)

9 Priority
Another common attribute is the thread priority, which is stored in the schema sched_param. Use the pthread_attr_getschedparam function and the pthread_attr_setschedparam function for storage.
# Include <pthread. h>
# Include <sched. h>
Pthread_attr_t ATTR;
Pthread_t tid;
Sched_param Param;
Int newprio = 20;

Pthread_attr_init (& ATTR );
Pthread_attr_getschedparam (& ATTR, & PARAM );
Param. sched_priority = newprio;
Pthread_attr_setschedparam (& ATTR, & PARAM );
Pthread_create (& tid, & ATTR, (void *) myfunction, myarg );

 

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.