简体   繁体   English

如何在用户级线程上运行功能?

[英]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. 所以我要创建自己的线程库,首先要有两个函数system_init()uthread create(void(* func)()) ,其中第一个应该初始化我的程序来处理用户线程。创建一个运行提供的功能的线程。 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() . 首先,我不知道如何运行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. 要在uthread_create()运行该函数,您需要将func推入堆栈。 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). 其中STACK_SIZE是一些预定义的常量(常量SIGSTKSZ应该起作用)。 After that, push func (and its relevant arguments) onto the stack. 之后,将func (及其相关参数)推入堆栈。

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. 出现分段错误的原因是ucontext_t类型包含一个指向其自身的指针,当您将其直接推入队列时,您正在进行复制。 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. 而是使一个指向ucontext_t的指针队列,然后从那里继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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