Advanced Programming for UNIX environment thread of reading notes (1)

Source: Internet
Author: User
Tags mutex terminates

1. Thread identification

Just as each process has a process ID, each thread also has a thread ID. The process ID is unique across the system, but unlike the thread ID, the thread ID is only valid in the process environment to which it belongs. The thread ID is represented by the pthread_t data type, and the Pthread_equal function is used to compare whether the two thread IDs are the same and the ID of the current thread can be obtained through the pthread_equal function.


#include <pthread.h>

int pthread_equal (pthread_t tid1,pthread_t tid2);


#include <pthread.h>

pthread_t pthread_self (void);


2. Creation of threads

A newly created thread can be implemented by the Pthread_create function.

Pthread_create function Prototypes:


When Pthread_create returns successfully, the memory unit pointed to by TIDP is referred to as the various properties used to customize the thread for the newly created thread's id,attr parameter. The new thread runs from the address of the START_RTN function with only one untyped pointer argument Arg. If you need to pass multiple arguments to a function, you need to put these parameters into the struct, and then pass the address of the struct as the arg parameter.


3. Process termination

If either thread calls Exit,_exit or _exit, the entire process terminates. Similarly, if the signal default action is to terminate the process, then the signal sent to the thread terminates the entire process.

In one of three ways to exit, you can stop 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) The thread is canceled by another thread in the same process.

(3) thread calls Pthread_exit.

Threads can wait for other threads in the same process to end by calling the Pthread_join function.


The thread that calls Pthread_join will always block, knowing that the waiting thread exits.


A thread can schedule a function to be called when it exits, similar to the function that a process can invoke when the process exits with the atexit function. This function is called the thread cleanup function. Threads can register multiple thread cleanup functions, which are executed in the reverse order of their registration.


4. The comparison between the line Hodohara language and the process primitive

We found that the system calls to the management thread had a lot in common with the system calls to the management process.


It is important to note that, by default, the terminating state of a thread is saved to call Pthread_join on that thread. If the thread is already in a detached state through Pthread_detach, the underlying resource of the threads is reclaimed as soon as it terminates, and the terminating state cannot be obtained through Pthread_join.


5. Thread Synchronization

A mutex (mutex) is essentially a lock that locks the mutex before accessing the shared resource, releasing the mutex after the access is complete. When the mutex is locked, any other thread that attempts to lock the mutex again will block until the locked thread releases the mutex.

Mutex variables are represented by the pthread_mutex_t data type. Before you use the pthread_mutex_t data type, be sure to initialize it. It can be set to constant Pthread_mutex_initializer, or it can be initialized with the Pthread_mutex_init function process.

If you want to lock the mutex, you need to call Pthread_mutex_lock, and if the mutex is locked, the calling thread will block until the mutex is unlocked. To unlock the mutex, you need to call Pthread_mutex_unlock. If you do not want to be blocked, you can use the Pthread_nutex_trylock function.


If you want to avoid permanent blocking, you can use the Pthread_mutex_timedlock function to set the thread blocking time. However, thepthread_mutex_timedlock function returns an error code etimedout when the thread is blocked to the time-out.

#include <pthread.h>

#include <time.h>

int Pthread_mutex_timedlock (pthread_mutex_t *restrict mutex,const struct timespec *restrict tsptr);

Example:

#include <stdio.h> #include <pthread.h> #include <time.h>int main (void) {int err;struct timespec tout; struct TM *tmp;char buf[64];p thread_mutex_t lock = Pthread_mutex_initializer;pthread_mutex_lock (&lock);p rintf (" Mutex is locked\n "); Clock_gettime (clock_realtime,&tout); tmp = LocalTime (&tout.tv_sec); Strftime (Buf,sizeof ( BUF), "%r", tmp);p rintf ("The currrent time is%s\n", buf); Tout.tv_sec + = 10;err = Pthread_mutex_timedlock (&lock,& Tout); Clock_gettime (clock_realtime,&tout); tmp = LocalTime (&tout.tv_sec); Strftime (Buf,sizeof (BUF), "%r", TMP);p rintf ("The currrent time is%s\n", buf); return-1;}

Read-write Locks: Read and write locks are similar to mutexes, but read-write locks allow for higher parallelism. There are three types of read/write locks: Locking state in write mode, locking state in read mode, 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.

To lock a read-write lock in read mode, you need to call Pthread_rwlock_rdlock. To lock a read-write lock in write mode, you need to call Pthread_rwlock_wrlock. No matter how you lock a read-write lock, you can call Pthread_rwlock_unlock to unlock it.


Similar to mutex, read-write locks can call Trylock to avoid thread clogging and to use Timedlock to set the waiting time.


Barrier: A barrier is a synchronization mechanism in which users coordinate multiple processes to work in parallel. The barrier allows each thread to wait until all of the cooperating threads reach a certain point and then continue execution from pity Dorado. The Pthread_join function is a barrier that allows one thread to wait until another thread exits.

The Pthread_barrier_init function can be used to initialize the barrier and initialize it with Pthread_barrier_destroy.

#include <pthread.h>

int Pthread_barrier_init (pthread_barrier_t *restrict barrier,const pthread_barrierattr_t *restrict attr,unsigned int count);

Where the count parameter specifies the number of threads that must reach the barrier before all threads are allowed to run down. Use the attr parameter to specify the properties of the Barrier object.

Threads that use pthread_barrier_wait enter hibernation when the barrier count is met, until the barrier count is met, and all threads are awakened.

int pthread_barrier_wait (pthread barrier_t *barrier)


Advanced Programming for UNIX environment thread of reading notes (1)

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.