int swRWLock_create(swLock *lock, int use_in_process) { int ret; bzero(lock, sizeof(swLock));//锁空间初始化 lock->type = SW_RWLOCK;//配置锁的范例为读写锁 pthread_rwlockattr_init(&lock->object.rwlock.attr);//linux函数,锁属性信息初始化 if (use_in_process == 1)//标志为在历程中利用,这里pthread开头的linux函数默认都是针对线程的 { //配置锁的属性信息,标志为在历程中利用 pthread_rwlockattr_setpshared(&lock->object.rwlock.attr, PTHREAD_PROCESS_SHARED); } if ((ret = pthread_rwlock_init(&lock->object.rwlock._lock, &lock->object.rwlock.attr)) < 0)//linux函数,锁信息初始化 { return SW_ERR; } /* * 配置锁的回调函数 */ lock->lock_rd = swRWLock_lock_rd; lock->lock = swRWLock_lock_rw; lock->unlock = swRWLock_unlock; lock->trylock = swRWLock_trylock_rw; lock->trylock_rd = swRWLock_trylock_rd; lock->free = swRWLock_free; return SW_OK; }
2、文件锁。
int swFileLock_create(swLock *lock, int fd) { bzero(lock, sizeof(swLock));//锁工具信息初始化 lock->type = SW_FILELOCK;//配置锁的范例为文件锁 /* * 配置锁的回调函数 */ lock->object.filelock.fd = fd; lock->lock_rd = swFileLock_lock_rd; lock->lock = swFileLock_lock_rw; lock->trylock_rd = swFileLock_trylock_rd; lock->trylock = swFileLock_trylock_rw; lock->unlock = swFileLock_unlock; lock->free = swFileLock_free; return 0; }
3、信号量锁
int swSem_create(swLock *lock, key_t key) { int ret; lock->type = SW_SEM;//配置锁范例为信号量锁 if ((ret = semget(key, 1, IPC_CREAT | 0666)) < 0)//建设信号量,这里配置的属性IPC_CREAT,这暗示这种信号量只能用于有亲缘干系的历程间 { return SW_ERR; } if (semctl(ret, 0, SETVAL, 1) == -1)//配置信号量ret的值为1 { swWarn("semctl(SETVAL) failed"); return SW_ERR; } lock->object.sem.semid = ret;//配置信号量ID /* * 配置回调函数 */ lock->lock = swSem_lock; lock->unlock = swSem_unlock; lock->free = swSem_free; return SW_OK; }
4、乐观锁
int swSpinLock_create(swLock *lock, int use_in_process) { int ret; bzero(lock, sizeof(swLock));//初始化锁工具 lock->type = SW_SPINLOCK;//配置锁的范例为乐观锁 //执行锁的初始化操纵,这里指明是在多历程中利用 if ((ret = pthread_spin_init(&lock->object.spinlock.lock_t, use_in_process)) < 0) { return -1; } /* * 配置回调函数信息 */ lock->lock = swSpinLock_lock; lock->unlock = swSpinLock_unlock; lock->trylock = swSpinLock_trylock; lock->free = swSpinLock_free; return 0; }
5、互斥量锁