关于并行编程中的链表

并发开发中,提到并行的使用链表来提高并行效率。

由于是多个用户操作,链表得加锁,但是锁也是需要占用资源的。

我们可以将所有的链表的操作封装为一个操作线程。
使用消息队列来通知这个线程来完成对这个队列操作,减少队列中等待锁同步的协同时间。


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;
}


上面代码不能直接运行,这里只是提出这个想法,以后如果有网友需要,我再来整理和完善。欢迎交流。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值