The 11th chapter--Thread

Source: Internet
Author: User
Tags constant error code mutex

1. The role of threads

(1) For program design: When one of our processes in a moment, need to do more than one event, there are generally two ways. One is the use of asynchronous programming mode, one is the use of multi-threaded synchronization mode. However, multithreaded synchronization mode is much more convenient than asynchronous mode. But for single-core systems, asynchronous programming patterns are often more efficient.

(2) For interactive programs, the general is to multi-threading, because when processing data, the interface is responsive.

Each thread contains the information necessary to represent the execution environment, including the identity thread ID in the process, a set of register values, stacks, scheduling priorities and policies, a signal mask word, an error variable, and thread-private data. All the information for a process is shared for all threads of the process.

2. Thread identification

#include <pthread.h>

//Compare thread IDs for equality: 0---Unequal, 0---equal
int pthread_equal (pthread_t t1, pthread_t T2);

Get the thread's own ID
pthread_t pthread_self ();

3. Thread creation

/* Create thread: 0---Successful; otherwise, when the error number is returned
successfully, the newly created thread ID is set to the memory unit that th points to.
The attr parameter is used to customize various thread properties, NULL---default properties. The
newly created thread runs from the address of the Func function,
which has only an untyped pointer argument arg 
*
/int pthread_create (pthread_t *th, 
                   const PTHREAD_ attr_t *attr, 
                   void * (*FUNC) (void *), 
                   void *arg);
Note: Thread creation does not guarantee which parameters will run first: whether to create the thread or the calling thread.

4. Thread termination

Three ways to exit a thread:

(1) can be simply returned from the startup routine, the return value is the thread's exit code

(2) A thread can be canceled by another thread in the same process

(3) Thread call Pthread_exit

Exit Current thread: Res is similar to void* Arg in the Pthread_create () function.

Other threads in the process can obtain this pointer by using the Pthread_join () function void pthread_exit (void *res);  /* Block the wait thread End Function: The calling thread will block until the specified thread calls Pthread_exit, returns from the startup routine, or is canceled.
0---success, otherwise the error number.

If a thread is simply returned from its startup routine, RES contains a return code, and if the thread is canceled, the memory unit specified by RES is set to pthread_canceled */int Pthread_join (pthread_t t, void **res);
A thread can request cancellation of other threads in the same process by calling the function.

Note: Pthread_cancel does not wait for the thread to terminate, it simply exits request int pthread_cancel (pthread_t t); A thread can schedule a function to be called when it exits, a thread can schedule several such functions,//Such functions are recorded in the stack and executed in the reverse order of registration.
This function is called cleanup function void Pthread_cleanup_push (void (*RTM) (void *), void *arg);
void Pthread_cleanup_pop (int execute);
/* Note: If the Execute parameter is set to 0, the cleanup function will not be called. When you call Pthread_exit (), when you call Pthread_cleanup_pop with a non-0 parameter when you respond to a cancellation request, Pthread_cleanup_pop will delete the "last" Pthread_cleanup_ The purge handler that is established by the push call, so both functions must be used in a pairing form in the same scope as the thread, and if the thread is simply terminated from the startup routine, its purge handler function is not invoked.
and due to different platforms, this return on FreeBSD and Mac OS X on the back of a segment error, the solution uses Pthread_exit ().  *///Following this process function, if Condition==true is returned from the middle, then//func_clean will not be executed void *func (void *arg) {Pthread_cleanup_push (Func_clean, Func_clean_ARG);
    if (condition) {return (void *) 1);
    } pthread_cleanup_pop (0);
return ((void *) 1);}//If the thread has been detached, calling Pthread_join will produce undefined behavior. We call Pthread_detach to detach the thread. 0---succeeded, otherwise the error number int Pthread_detach (pthread_t t) is returned;

5. Thread Synchronization

(1) Mutex amount

/*
The mutex is represented by the pthread_mutex_t data type and must be initialized first before using the mutex
. For statically allocated mutexes (static or global) can be set to constant
Pthread_mutex_initializer (only for statically allocated mutexes), or
through Pthread_mutex_init (). Following: 0---succeeds, otherwise returns the error number
*
/int pthread_mutex_init (pthread_mutex_t *m, const pthread_mutexattr_t *a);
int Pthread_mutex_destroy (pthread_mutex_t *m);


Locking, Unlock: 0---success, otherwise return error number
int Pthread_mutex_lock (pthread_mutex_t *m);
int Pthread_mutex_trylock (pthread_mutex_t *m);
int Pthread_mutex_unlock (pthread_mutex_t *m);

(2) Avoid deadlocks

If the same thread tries to lock the same mutex two times, a deadlock occurs. Additionally, if thread 1 obtains a mutex of a and requests mutex B, and thread 2 obtains the mutex B and requests A, a deadlock occurs. In the second case, we can use the Pthread_mutex_trylock interface to avoid deadlocks. If you already have some locks and the Pthread_mutex_trylock interface returns successfully, you can go ahead. But if you can't get a lock, you can release the lock you already have, clean it up, and then try again after some time. Alternatively, we can always keep A and B mutexes locked in the same order to avoid deadlocks.

Also, note that the granularity of the lock is not too coarse or too thin, which affects the concurrency of the program or increases the overhead of the system.

(3) Function Pthread_mutex_timedlock

/* When
a thread attempts to acquire a locked mutex, the function allows the bound thread to block the time.
However, when the timeout period is reached, the Pthread_mutex_timedlock does not lock the mutex
, but returns the error code etimedout, but if the mutex
is unlocked within the specified time, If the function succeeds, the mutex will lock the
return value: 0---success, or return error number
*/
#include <pthread.h>
#include <time.h>
int Pthread_mutex_timedlock (pthread_mutex_t *m, const timespec *ts);
Note: This time refers to the absolute time, that is, if M is unlocked before this cutoff time,
//Then this function returns immediately and does not death to the specified end time.

(4) Read/write lock

Read-write locks allow for higher parallelism. Only one thread at a time can occupy write-mode read-write locks, but multiple threads can occupy read-mode reading and writing locks at the same time. When a read-write lock is a write-lock state, all threads attempting to lock the lock will be blocked until the lock is unlocked. When a read-write lock reads the locking state, all threads attempting to lock it in read mode can be accessed, but any thread that locks the lock in write mode will block until all threads release their read lock. However, when a read-write lock is in a state that is locked in reading mode, and a thread attempts to acquire the lock in write mode, the read-write lock usually blocks subsequent reads-mode lock requests.

Read-write Lock: 0---success, or return error number
//for statically assigned mutex can be set to constant
//pthread_rwlock_initializer (only for statically allocated mutex)
int Pthread_ Rwlock_init (pthread_rwlock_t *rwlock_, 
                        const pthread_rwlockattr_t *attr);
int Pthread_rwlock_destroy (pthread_rwlock_t *l);

Locking, Unlock: 0---success, otherwise return error number
int Pthread_rwlock_rdlock (pthread_rwlock_t *l);
int Pthread_rwlock_wrlock (pthread_rwlock_t *l);
int Pthread_rwlock_unlock (pthread_rwlock_t *l);
int Pthread_rwlock_tryrdlock (pthread_rwlock_t *l);
int Pthread_rwlock_trywrlock (pthread_rwlock_t *l);
(5) Read-write lock with timeout

Read-write lock with timeout: 0---succeeded, otherwise the error number
int Pthread_rwlock_timedrdlock (pthread_rwlock_t *l, const TIMESPEC *ts) was returned;
int Pthread_rwlock_timedwrlock (pthread_rwlock_t *rwlock, const timespec *ts);
(6) Condition variables






















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.