- 论坛徽章:
- 11
|
本帖最后由 zylthinking 于 2017-12-01 13:28 编辑
这样最简单啊, 不用把脚本写到磁盘上去, 也不用部署还要记得装个脚本解释器, 也不用那一套罗嗦的进程间交互
最后这么干了, 管他呢, 看样子应该问题不大
- #include "macro.h"
- #include "zyl.h"
- #include "list_head.h"
- #include <stdlib.h>
- #include <sched.h>
- #include <errno.h>
- #include <unistd.h>
- #include <syscall.h>
- #define STACK_SIZE (8 * 1024 * 1024)
- typedef struct {
- list_head entry;
- void* (*func) (void*);
- void* arg;
- } thread_t;
- static lock_t lck = lock_initial;
- static list_head head = LIST_HEAD_INIT(head);
- static thread_t* stack_alloc()
- {
- thread_t* thead = NULL;
- lock(&lck);
- if (!list_empty(&head)) {
- list_head* ent = head.next;
- list_del(ent);
- thead = list_entry(ent, thread_t, entry);
- }
- unlock(&lck);
- if (thead == NULL) {
- thead = (thread_t *) malloc(sizeof(thread_t) + STACK_SIZE);
- }
- return thead;
- }
- static int child(void* arg)
- {
- thread_t* thead = (thread_t *) arg;
- thead->func(thead->arg);
- lock(&lck);
- while (!list_empty(&head)) {
- list_head* ent = head.next;
- list_del(ent);
- thread_t* ptr = list_entry(ent, thread_t, entry);
- free(ptr);
- }
- list_add(&thead->entry, &head);
- unlock(&lck);
- __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();
- 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_PARENT | CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_THREAD, thead);
- if (pid == -1) {
- free(thead);
- return errno;
- }
- return 0;
- }
复制代码
|
|