多线程中常见内存冗余法传递方式(内存冗余法,即在堆上开辟空间,然后通过参数传递过去)

内存冗余法,即在堆上开辟空间,然后通过参数传递过去。

为什么这样做,主要在于节省开销,比如,当我们在创建线程时,会用到函数:

1

2

int pthread_create(pthread_t *threadconst pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

  最后一个即传入的参数,如果只是传一个常规类型倒无所谓,但如果需要传递结构体:

1

2

3

4

5

typedef struct _ThreadInfo{

        int idx;

        char name[64];

        long long code;

}threadInfo;

  如果在栈上定义,那么在一定程度上,会占用很大一部份内存:threadInfo ti[1024];

此时,如果作为地址传递,在线程中的值,还会一样:

pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), (void *)&ti[i]);


这时,不仿考虑在堆上开辟空间,在传递过去,因为堆上总是比栈安全,内存更多:
threadInfo *ti = malloc(sizeof(threadInfo));
ti->idx = 100;
...

当然了,在线程中使用完后,记得释放一下这个内存。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值