【发布时间】:2016-02-16 15:43:58
【问题描述】:
我尝试实现一个包含任务控制块 (TCB) 的双向链表,每个任务控制块都包含一个指向函数的指针和一个 void 指针。我在不使用循环的情况下运行我的程序,它可以正常工作。但是,当我使用 for 循环时,它会停止工作。我的程序如下:
#include <iostream>
#include <stdlib.h>
using namespace std;
class TCB {
public:
void *data;
TCB *next;
TCB *prev;
public:
void (*myTask)(void *);
};
typedef void (*task)(void *data);
class Queue {
public:
TCB *head;
TCB *tail;
int numberOfElenments;
public:
void QueueInsert(void *data, task myTask);
void QueueRemove(TCB *task);
};
// Insert at tail
void Queue::QueueInsert(void *value, task myTask)
{
TCB *newTask = (TCB*)calloc(1, sizeof(TCB));
newTask->data = value;
newTask->myTask = myTask;
if(head == NULL) {
head = newTask;
tail = newTask;
} else {
tail->next = newTask;
newTask->prev = tail;
tail = newTask;
}
numberOfElenments++;
}
// Remove a particular node in queue
void Queue::QueueRemove(TCB *task)
{
if(head == NULL) {
// do nothing
}
if(task == head && task == tail) {
head = NULL;
tail = NULL;
} else if(task == head) {
head = task->next;
head->prev = NULL;
} else if(task == tail) {
tail = task->prev;
tail->next = NULL;
} else {
TCB *after = task->next;
TCB *before = task->prev;
after->prev = before;
before->next = after;
}
numberOfElenments--;
free(task);
}
void foo(void *data) {
cout<<"Hello world!"<<endl;
}
void foo2(void *data) {
cout<<"Hello, I am foo2!"<<endl;
}
int main(){
Queue *q;
q->QueueInsert(NULL, foo);
q->QueueInsert(NULL, foo2);
TCB *task;
task = q->head;
for(int i = 0; i < 2; i++) {
task->myTask(task->data);
task = task->next;
}
return 0;
}
我的程序有什么问题?
【问题讨论】:
-
“我的程序有什么问题?” - 主要是因为你几乎不使用 C++。为什么你认为你需要自制容器类?