"Apue" Reading notes 11th-Threads

Source: Internet
Author: User
Tags exit in

This chapter focuses on threading and how to use multithreading to perform multiple tasks in a single-process environment. Because multiple threads share their process space, the synchronization mechanism must be used to protect the consistency of the data.

I. The concept of threading

A typical Unix system can be seen as having only one control thread, and a process can only do one thing at a time. But with multi-threading, we can design the process to do more than one thing at the same time, and each thread handles its own separate tasks. all of the information for the process is shared with all threads of the process, including executable program text, the program's global memory and heap memory, stack, and file descriptors.

Two. Thread identification

#include <pthread.h>int pthread_equal (pthread_t tid1,pthread_t tid2); // returns a value other than 0 if equal, otherwise returns 0 pthread_t pthread_self (void); // returns the thread ID of the calling thread

Iii. thread creation, termination, and cleanup

int pthread_create (pthread_t *tid,const pthread_attr_t* attr,                   void* (* Start) (void*),void* arg); // return value: Returns 0 if successful, otherwise returns the error number

A single thread can exit in the following three ways, stopping its control flow without terminating the entire process.

    1. The thread is simply returned from the startup routine, and the return value is the thread's exit code.
    2. Threads can be canceled by other threads in the same process.
    3. The thread calls Pthread_exit.

However, these two functions have a limit, because they can be implemented as a macro, so it must be used in the same scope as the thread in a matching pair, the Pthread_cleanup_push macro definition can contain the character {, in this case the corresponding match character} is Pthread_ Appears in the CLEANUP_POP definition.

int pthread_join (pthread_t tid,void * * ptr); // returns 0 if successful, otherwise returns the error number

The calling thread will block until the specified thread calls Pthread_exit, returns from the startup routine, or is canceled. PTR will contain the return code.

If the thread takes the Pthread_self function to leave it in a detached state, the Pthread_join call fails. Returns EINVAL.

void pthread_cancel (pthread_t tid); // successful return 0, otherwise the error number is returned

A thread can schedule a function that needs to be called when it exits, similar to the function that a process needs to call when it can schedule a process to exit with the Atexit function. Threads can build multiple cleanup handlers, handlers in the stack, which means that their order is reversed from the order in which they are registered.

void Pthread_cleanup_push (void (*RTN) (void*),void *arg); void pthread_cleanup_pop (int execute);

The cleanup function is called when the thread executes the following action, and the invocation parameter is ARG.

    • When calling Pthread_exit
    • When responding to a cancellation request
    • When calling Pthread_cleanup_pop with a non-0 execute argument

If the Execute parameter is set to 0, the cleanup function will not be called.

Four. Thread synchronization

In order to maintain the consistency of data sharing, we take the mechanism of thread synchronization when multiple threads share the same memory. There are four ways to synchronize threads:

1. Mutex Amount

data can be secured by using Pthread's mutually exclusive interface to ensure that only one thread accesses the data at the same time. The mutex (mutex) is essentially a lock that locks the mutex before accessing the shared resource, releasing the lock on the mutex after the access is complete. When the mutex is locked, any other thread that attempts to lock the mutex again will be blocked until the current thread releases the mutex.

#include <pthread.h>int pthread_mutex_init (pthread_mutex_t *mutex,const PTHREAD_MUTEXATTR_ T *attr); int Pthread_mutex_destroy (pthread_mutex_t *mutex); int pthread_mutex_lock (pthread_mutex_t *mutex); int pthread_mutex_trylock (pthread_mutex_t *mutex); int pthread_mutex_unlock (pthread_mutex_t *mutex);

If the thread does not want to be blocked, it can use Pthread_mutex_trylock to try to lock the mutex. If the mutex is in an unlocked state when calling Pthread_mutex_trylock, then Pthread_mutex_trylock locks the mutex, does not block and returns 0. Otherwise pthread_mutex_trylock will fail. Cannot lock the mutex and return ebusy.

2. Read/write lock

Read-write locks are similar to mutexes, but read-write locks allow for higher parallelism. There are three types of reading and writing locks: Read mode lock state, write mode lock state, no lock state. 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 written to lock, 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 gain access, but if the thread wants to lock the lock in write mode, it must block all threads from releasing the read lock.

A read -write lock is also called a shared-exclusive lock, which is locked in shared mode when the read-write lock is locked in reading mode, and it is locked in exclusive mode when it is locked in write mode.

#include <pthread.h>int pthread_rwlock_init (pthread_rwlock_t *rwlock,const Pthread_ rwlockaddr_t* attr); int Pthread_rwlock_destroy (pthread_rwlock_t* rwlock); // returns 0 on success, otherwise returns an error number int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock); int pthread_rwlock_unlock (pthread_rwlock_t *rwlock);

3. Condition variables

Conditional variables provide a rendezvous place for multiple threads, allowing the thread to wait for a particular condition to occur in a non-competitive manner when used with a mutex.

The condition itself is protected by a mutex. The thread must first lock the mutex when it changes the condition state, and other threads will not perceive the change until the mutex is acquired, because the mutex must be locked before the condition can be evaluated.

intPthread_cond_init (pthread_cond_t *cond,pthread_condattr_t *attr);intPthread_cond_destroy (pthread_cond_t *cond);intPthread_cond_wait (pthread_cond_t *cond,pthread_mutex_t *mutex);intPthread_cond_timewait (pthread_cond_t *cond,pthread_mutex_t *Mutex,structtimespec*timeout); intPthread_cond_signal (pthread_cond_t *cond);intPthread_cond_broadcast (pthread_cond_t *cond);//successful return 0, Failure returns error number

#include <pthread.h>
structmsg*workq;pthread_cond_t Qready=pthread_cond_initializer;pthread_mutex_t Qlock=Pthread_mutex_initializer;voidProcess_msg (void){ structmsg*MP; for(;;) {Pthread_mutex_lock (&Qlock); while(qlock==NULL) {pthread_cond_wait (&qready,&Qlock); } MP=WORKQ; WORKQ=mp->M_next; Pthread_mutex_unlock (&Qlock); }}voidEnqueue_msg (structmsg*MP) {Pthread_mutex_lock (&Qlock); MP->m_next=WORKQ; WORKQ=MP; Pthread_mutex_unlock (&Qlock); Pthread_cond_signal (&qready);}

"Apue" Reading notes 11th-Threads

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.