以下代码未注释,未编译,未验证正确性
#define MAX_LIST 1024
typedef struct
{
char *data;
int isuse;
}data_t;
typedef struct
{
data_t data[MAX_LIST];
int index;
pthread_mutex_t mutex;
} wait_list;
wait_list * getwaitlist()
{
wait_list *list = calloc(1, sizeof(wait_list));
if (NULL != list)
{
pthread_mutex_init(&list->mutex, NULL);
}
return list;
}
void freewaitlist(wait_list *list)
{
pthread_mutex_destroy(&list->mutex);
free(list);
return;
}
void setwaitlist(wait_list *list, int index)
{
pthread_mutex_lock(&list->mutex);
if (1 != list->data[index&(MAX_LIST -1)].isuse)
{
///TODO: error
return ;
}
list->data[index&(MAX_LIST -1)].isuse = 2;
list->data[index&(MAX_LIST -1)].data = NULL;
if (list->index) == (index &(MAX_LIST -1)))
{
list->index = (list->index + 1)&(MAX_LIST -1);
}
pthread_mutex_unlock(&list->mutex);
return ;
}
int checkwaitlist(wait_list *list, char *buffer, int index)
{
pthread_mutex_lock(&list->mutex);
while (list->data[list->index].isuse == 2)
{
list->data[index&(MAX_LIST -1)].data = NULL;
list->data[list->index].isuse = 0;
list->index = (list->index + 1)&(MAX_LIST -1);
}
if (list->index == index &(MAX_LIST -1))
{
if (0 != list->data[list->index].isuse)
{
///TODO: error
return -1;
}
list->data[index&(MAX_LIST -1)].data = NULL;
list->data[list->index].isuse = 0;
list->index = (list->index + 1)&(MAX_LIST -1);
pthread_mutex_unlock(&list->mutex);
return 1;
}
while(0 != list->data[index&(MAX_LIST -1)].isuse)
{
pthread_mutex_unlock(&list->mutex);
usleep(20);
pthread_mutex_lock(&list->mutex);
}
list->data[index&(MAX_LIST -1)].data = buffer;
list->data[index&(MAX_LIST -1)].isuse = 1;
pthread_mutex_unlock(&list->mutex);
return 0;
}
char * makenextwaitlist(wait_list *list)
{
char *buffer = NULL;
pthread_mutex_lock(&list->mutex);
while (list->data[list->index].isuse == 2)
{
list->data[list->index].data = NULL;
list->data[list->index ].isuse = 0;
list->index = (list->index + 1)&(MAX_LIST -1);
}
if (list->data[list->index].isuse == 1)
{
buffer = list->data[list->index].data;
list->data[list->index].isuse = 0;
list->data[list->index].data = NULL;
list->index = (list->index + 1)&(MAX_LIST -1);
}
pthread_mutex_unlock(&list->mutex);
return buffer;
}
阅读(1181) | 评论(0) | 转发(0) |