我正在设计一个线程调度程序,该程序需要能够交换线程的上下文,以便所有线程都可以在单个线程NIOS-II Altera处理器上同时运行。我正在使用带有c的NiosII程序员来做这个项目。目前,我正在编写一个创建线程的函数。我需要做的是使用malloc在堆上为每个线程分配4KB作为其堆栈空间。然后我需要分配线程的SP地址值,这样我就可以稍后设置它的初始上下文。我想知道,如何获得malloc的顶部地址,就像我想做的那样:
SP=malloc的顶部地址-76
并将线程的上下文存储在堆栈的顶部。
我当前的代码:
struct TCB
{
int thread_id; //number representing what thread this TCB belongs to
int status; //running = 0, ready = 1, terminated = 2
int executionInfo; //number of time this thread has been run (incremented every time thread's context is restored)
char* SP; //SP used to store and restore context (stw RA, 0(SP) -- stw R1, 4(SP))
};
void mythread_create(int thread_id){
//use malloc to initialize stack space
char* stack;
stack = (char *) malloc(4000 * sizeof(char));
//create and initialize TCB for thread
struct TCB *TCB;
TCB.thread_id = thread_id;
TCB.status = 1;
TCB.executionInfo = 0;
TCB.SP =
}
#define bufflen something
char *buf = malloc(bufflen*sizeof(char));
char *topaddress =(buf+bufflen);
char *sp = topaddress-76;