Thread synchronization for Linux multi-thread programming

Source: Internet
Author: User
Thread synchronization for Linux multi-thread programming Thread synchronization for Linux multi-thread programming

Multithreading is used in the same memory space. there must be a basic principle:"Data between threads cannot be mutually damaged".

For example:

Two threads need to modify two variables. one thread sets both variables to 0 and the other to 1. the final result may be that the value of one of the variables is 1,

The other one is 0, which is caused by constant switching of the running environment.

The POSIX standard provides two synchronization mechanisms:"Mutex lock"And"Condition variable"

Mutex lock

The so-called mutex lock means that when a thread accesses data, the current data will be "locked". before the thread is unlocked, no other thread can lock (successfully locked) this variable.

If a thread has locked the mutex lock and the second thread is used to lock the mutex lock, the second thread suspends until the first thread unlocks the mutex lock. However

There are only two states, which will be inconvenient to use and the limitations are too small.

1. mutex lock initialization

Pthread_mutex_t mutex_t = PTHREAD_MUTEX_INITIALIZER;

Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutex_attr * attr );

Both can be initialized.

Second:

Pthread_mutex_attr * attr: the attribute of the mutex lock. Currently, it is set to the default value of NULL.

Note: "One lock can only be initialized once". the function is successfully executed 0 and the newly created mutex lock ID is placed in mutex. if the execution fails, an error number is returned.

2. release mutex lock

Int pthread_mutex_destroy (pthread_mutex_t * mutex );

3. lock

Int pthread_mutex_lock (pthread_mutex_t * mutex );

This function can lock the mutex lock pointed to by mutex. if mutex is locked, the thread that calls this function will be blocked until the mutex lock is released by other threads,

When pthread_mutex_lock is returned, the lock is successful.

4. trylock

Int pthread_mutex_trylock (pthread_mutex_t * mutex );

This function can try to lock the mutex lock. if it finds that the mutex lock has been locked, the function will not block and an error will be returned. Otherwise, the mutex lock will be locked by the caller.

5. unlock

Int pthread_mutex_unlock (pthread_mutex_t * unlock );

This function unlocks Mutex. 0 is returned for success, and 0 is returned for other values.

There is a rule for this function. The "unlock" button must be set to "unlock". otherwise, "unlock" will fail.

Instance:

1234567891011121314151617181920212223242526272829303132333435363738 # Include # Include # Include # Include Typedefstruct_thread_entry {intnum; pthread_mutex_t lock;} thread_entry; void * thread1 (void * arg) {thread_entry * t = (thread_entry *) arg; pthread_mutex_lock (& t-> lock ); t-> num = 200; printf ("% s \ n", "thread 1 is running"); pthread_mutex_unlock (& t-> lock );} void * thread2 (void * arg) {thread_entry * t = (thread_entry *) arg; pthread_mutex_lock (& t-> lock); t-> num = 10; printf ("% s \ n", "thread 2 is running"); pthread_mutex_unlock (& t-> lock);} intmain () {pthread_t tid [2]; char * ret; thread_entry * te = (thread_entry *) malloc (sizeof (thread_entry); te-> num = 10; pthread_mutex_init (& te-> lock, NULL ); pthread_create (& tid [0], NULL, (void *) thread1, (void *) te); pthread_create (& tid [1], NULL, (void *) thread2, (void *) te); pthread_join (tid [0], NULL); pthread_join (tid [1], NULL); pthread_mutex_destroy (& te-> lock); return0 ;}
Condition variable

A condition variable is a supplement to the mutex lock. it allows the thread to block and wait for another thread to send signals. when a signal is received, the blocked thread is awakened and attempts to lock the related mutex lock.

Conditional variables are used for waiting, not locking. Conditional variables are used to automatically block a thread until a special situation occurs. usually the conditional variables and mutex lock are used at the same time.

1. initialization

Conditional variables can also be initialized in two ways.

Pthread_cond_t t = PTHREAD_COND_INITIALIZER;

Int pthread_cond_init (pthread_cond_t * t, pthread_cond_attr * att );

0 is returned for success. Otherwise, an error occurs.

The second is the attribute of the condition variable, which is set to NULL here.

2. release condition variables

Int pthread_cond_destroy (pthread_cond_t * t );

0 is returned for success, and other errors are returned.

3. blocking on conditional variables

Int pthread_cond_wait (pthread_cond_t * t, pthread_mutex_t * mutex );

This function will unlock the mutex lock pointed to by * mutex and block the current thread on the condition variable pointed to by * t,

Blocked signals will be awakened in three situations

Call pthread_cond_signal, pthread_cond_broadcast, and interrupt signal.

Pay attention to the following two points:

The return of the pthread_cond_wait function does not mean that the condition value has changed. you must re-check the condition value.

When the pthread_cond_wait function returns but does not return, the corresponding mutex lock will be locked by the current thread, even if the function returns an error,

Therefore, after the function is returned, you need to re-test the condition value before locking the mutex. The best way is to call the pthread_mutex_wait () function cyclically.

For example

12345 Pthread_cond_t cond_t; pthread_mutex_lock (& mutex); while (! Cond_t) pthread_cond_wait (); pthread_mutex_unlock ();

Int pthread_cond_timedwait (pthread_cond_t * t, pthread_mutex_t * mutex, cont struct timespec * abstime );
0 is returned for success, and other errors are returned.

This function allows us to set the time to block the current thread. if the set time is exceeded, the current blocking status will be lifted even if no conditions are generated.

When the function returns, the mutex lock status is locked.

4. sending conditional signals

Int pthread_cond_signal (pthread_cond_t * t );

0 is returned for success, and other errors are returned.

This function removes the blocking on the condition variable.

If no thread is blocked on the condition variable, this function does not work.

5. release all threads blocked by this condition

Int pthread_cond_broadcast (pthread_cond_t * t );

0 is returned for success, and other errors are returned.

This function will wake up all threads that are blocked under the condition variable t. If no thread is blocked under the condition t, calling this function will not work.

Instance:

The following is a simple example of generation and Consumer. The Product is responsible for production. when 10 products are produced, the Consumer consumes 0.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 # Include # Include # Include # Include # Define MAXLIN extends cond_t; extends mutex_t; intproduct = 0; void * producer (void * arg) {pthread_mutex_lock (& mutex_t); while (product> 0) {pthread_cond_wait (& cond_t, & mutex_t) ;}while (product <= MAXLIN) {product ++; printf ("Producer: % d \ n", product) ;} pthread_cond_signal (& cond_t ); pthread_mutex_unlock (& mutex_t);} void * consumer (void * arg) {pthread_mutex_lock (& mutex_t); while (! (Product> 0) {pthread_cond_wait (& cond_t, & mutex_t) ;}while (product> 0) {product --; printf ("Consumer: % d \ n ", product);} pthread_cond_signal (& cond_t); consume (& mutex_t);} intmain () {pthread_mutex_init (& mutex_t, NULL); pthread_cond_init (& cond_t, NULL ); pthread_t t [2]; pthread_create (& t [0], NULL, (void *) producer, NULL); pthread_create (& t [1], NULL, (void *) consumer, NULL); // pthread_cond_signal (& cond_t); pthread_join (t [0], NULL); pthread_join (t [1], NULL); pthread_cond_destroy (& cond_t );; pthread_mutex_destroy (& mutex_t );}

After compilation, execute the following results:

 

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.