Generally, Uinx locks can be divided into three types [there may be more. I do not know]. Thread lock, semaphore, and record lock.
The thread lock is valid for the thread, and the semaphore and record lock are valid for the process.
Semaphore: The concept of process control in the OS class.
Advantage: high efficiency.
Disadvantage: deadlock is easy.
The disadvantage is too obvious. It is useless. Consider it later.
Thread lock: the basis of multithreading ..
The advantages and disadvantages are similar to semaphores.
The advantage of autolock is that it is valid within the lifecycle of a lock variable.
Put a cautolock directly in the function. All done ..
Class cautolock
{
PRIVATE:
Pthread_mutex_t * m_ptlock;
Public:
Cautolock (pthread_mutex_t * ptlock)
{
M_ptlock = ptlock;
Pthread_mutex_lock (m_ptlock );
}
~ Cautolock ()
{
Pthread_mutex_unlock (m_ptlock );
}
};
Record lock: it is the best candidate for the process-guard against process-down when the file handle is opened.
# Ifndef _ lockchk_h
# DEFINE _ lockchk_h
# Include <fcntl. h>
Int lock_reg (int fd, int cmd, int type, off_t offset, int whence, off_t Len)
{
Struct flock lock;
Lock. l_type = type;
Lock. l_start = offset;
Lock. l_whence = whence;
Lock. l_len = Len;
Return fcntl (FD, CMD, & lock );
}
Int lock_test (int fd, int cmd, int type, off_t offset, int whence, off_t Len)
{
Struct flock lock;
Lock. l_type = type;
Lock. l_start = offset;
Lock. l_whence = whence;
Lock. l_len = Len;
If (fcntl (FD, CMD, & lock) <0)
Return-99;
If (lock. l_type = f_unlck)
Return 0;
Return lock. l_pid;
}
# Define read_lock (FD, offset, whence, Len )/
Lock_reg (FD, f_setlk, f_rdlck, offset, whence, Len)
# Define readw_lock (FD, offset, whence, Len )/
Lock_reg (FD, f_setlkw, f_rdlck, offset, whence, Len)
# Define write_lock (FD, offset, whence, Len )/
Lock_reg (FD, f_setlk, f_wrlck, offset, whence, Len)
# Define writew_lock (FD, offset, whence, Len )/
Lock_reg (FD, f_setlkw, f_wrlck, offset, whence, Len)
# Define un_lock (FD, offset, whence, Len )/
Lock_reg (FD, f_setlk, f_unlck, offset, whence, Len)
# Define is_read_lockable (FD, offset, whence, Len )/
Lock_test (FD, f_getlk, f_rdlck, offset, whence, Len)
# Define is_write_lockable (FD, offset, whence, Len )/
(Lock_test (FD, f_getlk, f_wrlck, offset, whence, Len) = 0)
# Endif
# Define path "/var/lock/r2b_shop_re_present"
# Define lock_file (SSN) (STD: string (PATH) + SSN). c_str ()
Int g_lockid = 0;
Bool trylock (const string & SSN)
{
G_lockid = open (lock_file (SSN. c_str (), o_wronly | o_creat );
Int iret = is_write_lockable (g_lockid, 0, seek_set, 0 );
Close (g_lockid );
Return iret;
}
Void lock (const string & SSN)
{
If (g_lockid = open (lock_file (SSN. c_str (), o_wronly | o_creat) <0 ){
Cout <SSN <"file open failed" <Endl;
Return;
} Else {
Write_lock (g_lockid, 0, seek_set, 0 );
}
}
Void unlock (const string & SSN)
{
If (0! = G_lockid)
Un_lock (g_lockid, 0, seek_set, 0 );
Close (g_lockid );
}