alibaba / PhotonLibOS

Probably the fastest coroutine lib in the world!

Home Page:https://PhotonLibOS.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

What is 'randomizer' in thread_create for?

KiventD opened this issue · comments

thread* thread_create(thread_entry start, void* arg,
            uint64_t stack_size, uint16_t reserved_space) {
    RunQ rq;
    if (unlikely(!rq.current))
        LOG_ERROR_RETURN(ENOSYS, nullptr, "Photon not initialized in this vCPU (OS thread)");
    size_t randomizer = (rand() % 32) * (1024 + 8);
    stack_size = align_up(randomizer + stack_size + sizeof(thread), PAGE_SIZE);
    char* ptr = (char*)photon_thread_alloc(stack_size);
    auto p = ptr + stack_size - sizeof(thread) - randomizer;
    (uint64_t&)p &= ~63;
    auto th = new (p) thread;
    th->buf = ptr;
    th->stackful_alloc_top = ptr;
    th->start = start;
    th->stack_size = stack_size;
    th->arg = arg;
    auto sp = align_down((uint64_t)p - reserved_space, 64);
    th->stack.init((void*)sp, &_photon_thread_stub, th);
    AtomicRunQ arq(rq);
    th->vcpu = arq.vcpu;
    arq.vcpu->nthreads++;
    arq.insert_tail(th);
    return th;
}

Photon uses 'thread_create' to create threads. I wonder what is the purpose of 'randomizer' here. Dose it improve any performance and isn't it a waste of memory? Thanks!

It's helpful for avoiding cache collisions.

Thanks for your reply!