linux程序退出资源回收,通过clone 创造线程, 怎么在线程退出后回收栈空间

最后这么实现了, 应该问题不大

#include "macro.h"

#include "list_head.h"

#include 

#include 

#include 

#include 

#define STACK_SIZE (8 * 1024 * 1024)

typedef struct {

list_head entry;

void* (*func) (void*);

void* arg;

} thread_t;

static thread_t* static_thread = NULL;

static thread_t* stack_alloc(int32_t size)

{

thread_t* thead = __sync_lock_test_and_set(&static_thread, NULL);

if (thead == NULL) {

thead = (thread_t *) malloc(sizeof(thread_t) + size);

}

return thead;

}

static int child(void* arg)

{

thread_t* thead = (thread_t *) arg;

thead->func(thead->arg);

thead = __sync_lock_test_and_set(&static_thread, thead);

if (thead != NULL) {

free(thead);

}

__asm__(

"movq $" str(__NR_exit) ", %rax\n"

"movq $0, %rdi\n"

"syscall\n"

);

return 0;

}

int mythread_create(void* (*func) (void*), void* arg)

{

thread_t* thead = stack_alloc(STACK_SIZE);

if (thead == NULL) {

return ENOMEM;

}

char* stack = (char *) (thead + 1) + STACK_SIZE;

thead->arg = arg;

thead->func = func;

pid_t pid = clone(child, stack, CLONE_FILES | CLONE_FS |

CLONE_VM | CLONE_IO | CLONE_SIGHAND | CLONE_THREAD, thead);

if (pid == -1) {

int n = errno;

free(thead);

return n;

}

return 0;

}

【 在 jackwish 的大作中提到: 】

: 如果用 libc ,munmap 在回收栈的时候栈不是正在用吗?不汇编不行啊……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值