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、互斥量锁