Linux -Blue forest free software | Return to home page | Site Map | Search WWW | Contact Us | -->
Your current position : Homepage > Free Software > Technological exchanges >Application Programming -->


    

Blue Forest http://www.lslnet.com at 2:08 p.m. on August 16, 2006


Interpretation : posted pthread (c)

Posix Threads Programming Guide (3)



:

1. Mutex
2. Variable Conditions
3. Lights
4. Asynchronous signal
5. Other Synchronization
On the author


Related content :

(1) to establish and abolish Thread
(2) Thread private data




Thread Synchronization
Yang sandbank (pubb@163.net)
October 2001

This is a program on Posix Threads column. Based on the concept of the author explained, would you detail Posix Thread Library API. Title III of this paper will be on your thread synchronization.
1. Mutex
Similarly, despite the Posix Thread Semaphore IPC mechanisms can be used to achieve Mutex mutex function, it is clear that the function semphore too strong, as defined in the Posix Thread devoted to a separate thread synchronization mutex function.

1. Creation and destruction
There are two ways to create Mutex, static and dynamic way way. POSIX defines a macro PTHREAD_MUTEX_INITIALIZER Mutex to static initialization, as follows :
Pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
In LinuxThreads implementation, pthread_mutex_t is a structure, but structure PTHREAD_MUTEX_INITIALIZER is a constant.

Dynamic mode is used pthread_mutex_init () function Mutex initialization, the API defined as follows :
Int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)
Mutex mutexattr used for the purpose designated, which attributes (see below), if used for the NULL default attributes.

Pthread_mutex_destroy () for the write-off of a mutex lock API is defined as follows :
Int pthread_mutex_destroy (pthread_mutex_t *mutex)
Mutex means that the destruction of a release of the resources it has occupied, and at the request of the current open. As in Linux, Mutex not occupy any resources, the LinuxThreads pthread_mutex_destroy () Inspection locked outside the state (the state is locked return EBUSY) no other action.

2. Attribute Mutex
Mutex attributes specified in the creation of the lock, locking in LinuxThreads realized only one type attributes of different types of locks have been locked in an attempt to lock the mutex locking am different. At present (glibc2.2.3, linuxthreads0.9) value of the four options :

PTHREAD_MUTEX_TIMED_NP This is the default value, which is an ordinary lock. When a thread lock, the rest of the thread will be locked into a pending request queue and in accordance with priorities agreed after unlocking locked. This strategy locks to ensure the fairness of the distribution of resources.
PTHREAD_MUTEX_RECURSIVE_NP, nest lock with a lock to allow one thread to many successful and unlock unlocking many times. If the request is different threads, thread locking in unlocking re-competition.
PTHREAD_MUTEX_ERRORCHECK_NP led to the wrong lock with a lock request if the same thread, then return EDEADLK, PTHREAD_MUTEX_TIMED_NP with the same type of action. This will ensure that there will not be locked when not allow many of the most simple deadlock.
PTHREAD_MUTEX_ADAPTIVE_NP meet locks, lock the simplest type of action only after waiting for unlocking compete.

3. Lock operation
Pthread_mutex_lock include locking lock operation (), unlocking pthread_mutex_unlock () and testing locked pthread_mutex_trylock (), regardless of what type of lock can be two different threads simultaneously. and must wait for unlocking. For ordinary locks and adapt to lock types, unlocking the same process can be any thread; Error must be locked by the locking and unlocking were valid, the return EPERM; for nest lock files and to achieve those required by the unlocking locked, but the results showed no such restrictions, the difference has not been explained. The thread in the same process, if not after unlocking locked, it could no longer obtain any other threads are locked.

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

Pthread_mutex_trylock () semantics and pthread_mutex_lock () similar to the lock has been occupied in return EBUSY rather than waiting for history.

4. Other
POSIX thread locking mechanism Linux is not canceled, therefore, will not delay the abolition of thread types of signals received from the abolition of locking wait. It is worth noting that if the thread after unlocking locked in before the cancellation will always remain locked locks, so if there are points in the key section are abolished, or set up a type of asynchronous canceled, the callback function must withdraw from unlocking.

The locking mechanism is also asynchronous signal is not safe, that is to say, should not be used in signal processing Mutex, easily deadlock.

2. Variable Conditions
Variable Conditions are shared among threads in the overall use of a synchronization mechanism variables, including two movements : one thread to wait for "the establishment of conditions of variable conditions" and history; Another thread so that the "conditions for the establishment of" (given conditions to signal). To prevent competition, the variable conditions and always use a mutex lock together.

1. Creation and cancellation
Mutex and variable conditions, the two building methods have static dynamic and static PTHREAD_COND_INITIALIZER constant use, as follows :
Pthread_cond_t cond=PTHREAD_COND_INITIALIZER

Calling pthread_cond_init dynamic mode () function is defined as follows : API
Int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *cond_attr)

Although the POSIX standard for the definition of the attribute variable conditions, but did not realize LinuxThreads, cond_attr normally NULL values, which have been neglected.

Cancellation of a variable conditions necessary to redeploy pthread_cond_destroy (), not only in terms of the variables on the waiting thread can be canceled when the variable conditions, the return EBUSY. No Linux distribution because of the conditions and what the variables, including the write-off to check whether there are any pending action only thread. API is defined as follows :
Int pthread_cond_destroy (pthread_cond_t *cond)

2. Wait and inspire
Int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
Int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)

Wait for conditions to be in two ways : They wait pthread_cond_wait () and the time to wait pthread_cond_timedwait (), which means if in a given moment of time to wait before the conditions are not satisfied, then return ETIMEOUT end wait abstime them with the time () system call the same time the absolute sense, there is 0 expressed Jiatelinni Time at 12:00 a.m. on January 1, 1970 1700 0秒.

Whatever the wait, and must meet a mutex lock to prevent more threads also request pthread_cond_wait () (or pthread_cond_timedwait () 165) competitive conditions (Race Condition). Mutex mutex lock to be an ordinary (PTHREAD_MUTEX_TIMED_NP) or adjust to lock (PTHREAD_MUTEX_ADAPTIVE_NP) and in calling pthread_cond_wait () to be locked up by the thread (pthread_mutex_lock ()), while in queue waiting for updated conditions before mutex remain locked, and wait before entering the thread linking unlocking. In order to satisfy the conditions to leave pthread_cond_wait (), will be re-mutex locking, and access to pthread_cond_wait () before the locking action counterparts.

There are two forms of excitation conditions, pthread_cond_signal () activated by a thread waiting for the conditions, the existence of many waiting threads into teams according to a sequence of activation; And pthread_cond_broadcast () activate all waiting thread.

3. Other
Pthread_cond_wait () and pthread_cond_timedwait () for the lifting point has been achieved, it would immediately resume at the waiting threads operating at left pthread_cond_wait reacquired mutex (). Then abolition movement. This means that if pthread_cond_wait () has been canceled, mutex lock is to maintain the state, hence the need to withdraw from the callback function defined for unlocking.

Mutex focus on the following examples demonstrate the combined use of variables and conditions, and conditions for cancellation of the pending action. In those cases, there are two threads was activated, and await with a variable conditions, if not from the use of callback function (see example of the Notes), tid2 in pthread_mutex_lock () a permanent wait. If the use of callback function, and the main thread tid2 waiting for the conditions to stimulate the normal working conditions.


#include "Stdio.h>
#include "Pthread.h>
#include "Unistd.h>

Pthread_mutex_t mutex;
Pthread_cond_t cond;

Void * child1 (void *arg)
{
Pthread_cleanup_push (pthread_mutex_unlock, &mutex); LEAVES OF 13 SPECIES OF LAURACEAE comment one */
While (1) (
Printf ( "get one thread running \n");
Printf ( "1 pthread_mutex_lock returns %d\n thread."
Pthread_mutex_lock (&mutex));
Pthread_cond_wait (&cond, &mutex);
Printf ( "1 condition applied\n thread");
Pthread_mutex_unlock (&mutex);
Sleep (5);
}
Pthread_cleanup_pop (0); LEAVES OF 13 SPECIES OF LAURACEAE comment two */
}

Void *child2 (void *arg)
{
While (1) (
Sleep (3); LEAVES OF 13 SPECIES OF LAURACEAE comment */ 3
Printf ( "2 get running.\n thread");
Printf ( "2 pthread_mutex_lock returns %d\n thread."
Pthread_mutex_lock (&mutex));
Pthread_cond_wait (&cond, &mutex);
Printf ( "2 thread condition applied\n");
Pthread_mutex_unlock (&mutex);
Sleep (1);
}
}

Int main (void)
{
Int tid1, tid2;

Printf ( "Panorama, the condition variable test\n");
Pthread_mutex_init (&mutex, NULL);
Pthread_cond_init (&cond, NULL);
Pthread_create (&tid1, NULL, child1, NULL);
Pthread_create (&tid2, NULL, child2, NULL);
Do{
Sleep (2); LEAVES OF 13 SPECIES OF LAURACEAE comment 4 */
Pthread_cancel (tid1); LEAVES OF 13 SPECIES OF LAURACEAE comment 5 */
Sleep (2); LEAVES OF 13 SPECIES OF LAURACEAE comment 6 */
Pthread_cond_signal (&cond);
}while (1);
Sleep (100);
Pthread_exit (0);
}



If we do nothing Notes 5 pthread_cancel () movements, even in the absence of those who sleep () delay operations, the normal work child1 and child2. Note 3 and Note 4 child1 makes a complete cancellation of the delayed action so child1 child2 can enter a request from the lock operation. Note 1 and Note 2 If there is no definition of a callback function, the system will put up a request child2 locked in place; If not done while the delay Note 3 and Note 4, child1 child2 complete abolition movements in the past under control, thereby lock for the smooth implementation of the operation. it may flag in pthread_cond_wait (), which have operated for the mutex. Child1 function variables are given in standard conditions : callback function used in a way to protect and wait for the conditions identified, pthread_cond_wait () to return after unlocking.

Variable Conditions asynchronous signal mechanism is not safe, say, signal processing function call pthread_cond_signal () or pthread_cond_broadcast () likely lead to deadlock.

3. Lights
Mutex conditions with variable signal and the main difference is that "light" concept, lights it means that resources are available, it means that light can not be used to eliminate. If that means focusing on two simultaneous "wait" operation, that is not the resources, the mechanism will focus on features signal that this resource can be used; No waiting for the unlocking threads or excitation conditions are not meaningless, and did not wait for the lights of the thread while the operation is effective and can maintain the status lights. Of course, this also means more primitive operating expenses.

In addition to the application of signal lights / lights to eliminate this dual lights, the lights can be used in a number greater than 1, said resources greater than 1, then it can be said that multiple lights.

1. Creation and cancellation
POSIX standard definition of the famous signal lights and two unknown signal, but only the realization of LinuxThreads unnamed lights, and lights in addition to always be known for many processes, and the use of lights and the unknown is not a great deal of difference, so far unnamed lamps discussed below.

Int sem_init (sem_t *sem, pshared int, unsigned int value)
This is the API to create signal, the initial value for the lights, said it pshared more for the process of sharing rather than a process. LinuxThreads not signal multi-sharing process, the value of all non-0 pshared importation will make sem_init () return -1, and home errno to ENOSYS. Sem characterized by variable initialization good signal for the following features and eliminate lights operating.

Int sem_destroy (sem_t * sem)
No request has been canceled signal sem thread waiting for the signal, or else return -1, and home errno to EBUSY. In addition, the signal cancellation function LinuxThreads do other movements.

2. Features and eliminate lights
Int sem_post (sem_t * sem)
Signal processing will increase while the value of one atom to express an increase of the resources.

Int sem_wait (sem_t * sem)
Int sem_trywait (sem_t * sem)
Sem_wait () to wait for the lights to operate pending the lights (lights> 0), and then to reduce the signal atomic 1, and return. Sem_trywait () sem_wait () version of nonobstructive, signal count greater than 0, 0 atoms to minus 1 and return, the immediate return -1, errno home to EAGAIN.

3. HEC acquisition value
Int sem_getvalue (sem_t * sem, int * sval)
Counting the sem reading lights, keep in *sval, and return 0.

4. Other
Sem_wait () was achieved for the lifting, but also in support of atoms, "the exchange also" directed the architecture, sem_post () is the only asynchronous signal processing function for the safety of asynchronous signal POSIX API.

4. Asynchronous signal
As LinuxThreads is in the process of achieving nuclear outside of the use of nuclear lightweight threads, based on the kernel threads for asynchronous signal operation is effective. However, asynchronous signal is always sent to a real process, it is impossible to achieve the required standard POSIX "signals reach a certain process, then by the process will be distributed to all signals without obstructing the signal thread" original language, which only affect a thread.

POSIX asynchronous signal is also available from a standard C functions, including Signal Sets Management (sigemptyset (), sigfillset (), sigaddset (), sigdelset (), sigismember (), etc.), installation of signal processing function (sigaction ()), signal congestion control (sigprocmask ()), the signal was blocked inquiries (sigpending ()), signals wait (sigsuspend ()). kill them and send the signal () function could be realized processes asynchronous signals. LinuxThreads thread sealing around the sigaction (), Mr raise (), this section focuses on the mid-LinuxThreads asynchronous signal function, including pthread_sigmask (), pthread_kill () sigwait () function. Undoubtedly, all POSIX threads are available for asynchronous signal function.

Int pthread_sigmask (int how, const sigset_t *newmask, sigset_t *oldmask)
Thread installed signal shielding code, semantic and sigprocmask (), but not allowed to shield Cancel Restart signal and the signal is not allowed to respond to the protection. Signals were kept in the parade were shielding the signal from sigpending () function removed.

Int pthread_kill (pthread_t thread, int signo)
No. thread to thread signo signal transmission. Thread by thread in the realization of its position corresponding to the process after its use kill () system call to complete transmission.

Int sigwait (const sigset_t *set, int *sig)
Linking thread, one of the signals specified in the pending arrival set, the signal will reach into *sig China. POSIX standard in calling sigwait () signal wait until all the threads should be shielding the signal process to ensure that only sigwait () to obtain the transfer of the signal, it needs to wait for the asynchronous signal synchronization, in the creation of any thread should always call before pthread_sigmask () shielding the signal processing. Moreover, calling sigwait (), attached to the original signal on the signal processing function will be deployed.

Cancel if the waiting period to receive signals immediately from the wait is sigwait () was achieved for the lifting points.

5. Other Synchronization
Apart from the above discussion synchronized manner, other means of communication for many processes LinuxThreads is also available, such as paper, the IPC (pipes, Unix domain socket), Message Queue (Sys.V or Posix), and other System V signal. Only point that needs attention, as it is shared memory LinuxThreads the nuclear area, and shared file system attributes and share signal processing and sharing Wenjianmiaoshufu independent look at the process.

























 Privacy Policy  Copyright © 1999-2000 LSLNET.COM. All rights reserved. Blue Forest website owners. E-mail : Webmaster@lslnet.com