myxce/src/lib/mylock.c
2025-11-03 18:19:59 +08:00

212 lines
3.5 KiB
C

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "mylock.h"
int mylock_init(mylock_t* l)
{
if (l == NULL) {
return -EINVAL;
}
return pthread_mutex_init(l, NULL);
}
void mylock_fini(mylock_t* l)
{
if (l == NULL) {
return;
}
pthread_mutex_destroy(l);
}
int mylock_try(mylock_t* l)
{
if (l == NULL) {
return -EINVAL;
}
return pthread_mutex_trylock(l);
}
int mylock_lock(mylock_t* l)
{
if (l == NULL) {
return -EINVAL;
}
return pthread_mutex_lock(l);
}
int mylock_unlock(mylock_t* l)
{
if (l == NULL) {
return -EINVAL;
}
return pthread_mutex_unlock(l);
}
int cbuf_init(cbuf_t* b,
int cap,
int isize)
{
if ((b == NULL) || (cap <= 0) || (isize <= 0)) {
return -EINVAL;
}
b->ncap = cap;
b->isize = isize;
b->data = (void*)calloc(cap, isize);
if (b->data == NULL) {
return -EINVAL;
}
b->head = 0;
b->len = 0;
pthread_mutex_init(&(b->mutex), NULL);
pthread_cond_init(&(b->condget), NULL);
pthread_cond_init(&(b->condput), NULL);
return 0;
}
void cbuf_fini(cbuf_t* b)
{
if (b == NULL) {
return;
}
if (b->data != NULL) {
free(b->data);
b->data = NULL;
}
pthread_mutex_destroy(&(b->mutex));
pthread_cond_destroy(&(b->condput));
pthread_cond_destroy(&(b->condget));
}
int cbuf_put(cbuf_t* b,
void* it)
{
int i;
if ((b == NULL) || (it == NULL)) {
return -EINVAL;
}
pthread_mutex_lock(&(b->mutex));
while (b->len == b->ncap) {
pthread_cond_wait(&(b->condput),
&(b->mutex));
}
i = (b->head + b->len) % b->ncap;
memcpy((void*)((char*)b->data) + b->isize * i,
it, b->isize);
b->len++;
pthread_cond_signal(&(b->condget));
pthread_mutex_unlock(&(b->mutex));
return 0;
}
int cbuf_tryput(cbuf_t* b,
void* it)
{
int i;
int rc = 0;
if ((b == NULL) || (it == NULL)) {
return -EINVAL;
}
pthread_mutex_lock(&(b->mutex));
if (b->len < b->ncap) {
i = (b->head + b->len) % b->ncap;
memcpy((void*)((char*)b->data) + b->isize * i,
it, b->isize);
b->len++;
pthread_cond_signal(&(b->condget));
} else {
rc = -EAGAIN;
}
pthread_mutex_unlock(&(b->mutex));
return rc;
}
int cbuf_get(cbuf_t* b,
void* it)
{
if ((b == NULL) || (it == NULL)) {
return -EINVAL;
}
pthread_mutex_lock(&(b->mutex));
while (b->len == 0) {
pthread_cond_wait(&(b->condget),
&(b->mutex));
}
memcpy(it, (void*)((char*)b->data) + b->isize * b->head,
b->isize);
b->head = (b->head + 1) % b->ncap;
b->len--;
pthread_cond_signal(&(b->condput));
pthread_mutex_unlock(&(b->mutex));
return 0;
}
int my_rwlock_init(my_rwlock_t *l) {
if ( l == NULL) {
return -EINVAL;
}
return pthread_rwlock_init(l, NULL);
}
void my_rwlock_fini(my_rwlock_t *l) {
if (l == NULL) {
return;
}
pthread_rwlock_destroy(l);
}
int my_rwlock_unlock(my_rwlock_t *l) {
if (l == NULL) {
return -EINVAL;
}
return pthread_rwlock_unlock(l);
}
int my_rwlock_rlock(my_rwlock_t *l) {
if (l == NULL) {
return -EINVAL;
}
return pthread_rwlock_rdlock(l);
}
int my_rwlock_wlock(my_rwlock_t *l) {
if (l==NULL) {
return -EINVAL;
}
return pthread_rwlock_wrlock(l);
}