在并发开发中,提到并行的使用链表来提高并行效率。
由于是多个用户操作,链表得加锁,但是锁也是需要占用资源的。
我们可以将所有的链表的操作封装为一个操作线程。
使用消息队列来通知这个线程来完成对这个队列操作,减少队列中等待锁同步的协同时间。
void* process_proc_message(void* arg)
{
int msqid;
key_t key;
int fd;
char msg_buf[PROC_MSG_MAX_LEN]={0};
int long_len = sizeof(long);
//创建一个文件,用于
if ((fd = open(PROC_MSG_FILE, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)) == -1)
{
perror("[PROC_MSG_FILE] open file error");
exit(-1);
}else{
close(fd);
}
// 获取key值
if ((key = ftok(PROC_MSG_FILE, 0)) < 0)
{
perror("[PROC_MSG_FILE] ftok error");
exit(-1);
}
// 创建消息队列
if ((msqid = msgget(key, IPC_CREAT | 0777)) == -1)
{
perror("msgget error");
exit(1);
}
int msg_len = 0;
//创建一个 模型进程 管理队列
modle_channle_t *model_proc_info = (modle_channle_t *)malloc(sizeof(modle_channle_t));
if (model_proc_info == NULL)
{
fprintf(stderr, "Failed to malloc memory, errno:%u, reason:%s\n",
errno, strerror(errno));
return NULL;
}
proc_list = &model_proc_info->list_node;
init_list_head(proc_list);
while (1)
{
if (is_exit) break;
msg_len = msgrcv(msqid, msg_buf, PROC_MSG_MAX_LEN, -SYSTEM_MESSAGE_UNITE_OPT, IPC_NOWAIT); // 系统统一处理的消息
if(msg_len <= 0 && errno != ENOMSG){
perror("[msgrcv] receive process message error");
exit(-1);
}
long message_type = *((long*)msg_buf);
//处理消息
if (SYSMSG_TYPE_CREATE == message_type)
{
create_communicate_channle((message_create *)(msg_buf + long_len));
}
else if (SYSMSG_TYPE_DESTORY == message_type)
{
destory_communicate_channle(*(int *)(msg_buf + long_len));
}
else if (SYSMSG_TYPE_ONLINE == message_type)
{
online_communicate_channle(*(int *)(msg_buf + long_len));
}
else if (SYSMSG_TYPE_OFFLINE == message_type)
{
offline_communicate_channle(*(int *)(msg_buf + long_len));
}
// break;
}
return NULL;
}
上面代码不能直接运行,这里只是提出这个想法,以后如果有网友需要,我再来整理和完善。欢迎交流。