简体   繁体   中英

How do I run a function on a user level thread?

So I'm creating my own thread library and to start off I have two functions system_init() and uthread create(void (* func)( )) the first of which is supposed to initialize my program for handling user threads and the second which creates a thread that runs the function provided. These functions are as follows:

#include <stdio.h>
#include <queue>
#include <ucontext.h>
#include <semaphore.h>
#include <unistd.h>



std::queue<ucontext_t> *readyQueue;
int numKernelThreads;
int numIOWaitingProcesses;
sem_t sem;

void system_init() {
        numKernelThreads = 0;
        numIOWaitingProcesses = 0;
        sem_init(&sem, 0, 1);
}



int uthread_create(void (* func)()) {
        ucontext_t context;
        getcontext(&context);
        makecontext(&context, func, 0);
        readyQueue->push(context);
}

I am having a few problems with it. First off I don't know how to run the function I provide in uthread_create() . Secondly I am getting segmentation faults when I push the context onto the queue. I'm just completely lost and would appreciate some direction. Thanks.

To run the function in uthread_create() , you need to push func onto the stack. Initialize the stack with something like

char* stack = new char[STACK_SIZE];
context.uc_stack.ss_sp = stack;
context.uc_stack.ss_size = STACK_SIZE;

where STACK_SIZE is some pre-defined constant (the constant SIGSTKSZ should work). After that, push func (and its relevant arguments) onto the stack.

The reason your getting segmentation faults is because the ucontext_t type contains a pointer to itself, and when you push it directly onto the queue you're making a copy. Then, the new copy points to the old data member, and when the old data member gets deleted, you will have a segfault. Instead, make a queue of pointers to ucontext_t and proceed from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM