A thread-safe, but non-scalable, filetable

上级 229f28b7
...@@ -5,6 +5,7 @@ public: ...@@ -5,6 +5,7 @@ public:
filetable() : ref_(1) { filetable() : ref_(1) {
for(int fd = 0; fd < NOFILE; fd++) for(int fd = 0; fd < NOFILE; fd++)
ofile_[fd] = nullptr; ofile_[fd] = nullptr;
initlock(&lock_, "filetable", 0);
} }
filetable(const filetable &f) : ref_(1) { filetable(const filetable &f) : ref_(1) {
...@@ -14,6 +15,7 @@ public: ...@@ -14,6 +15,7 @@ public:
else else
ofile_[fd] = nullptr; ofile_[fd] = nullptr;
} }
initlock(&lock_, "filetable", 0);
} }
~filetable() { ~filetable() {
...@@ -23,29 +25,40 @@ public: ...@@ -23,29 +25,40 @@ public:
ofile_[fd] = 0; ofile_[fd] = 0;
} }
} }
destroylock(&lock_);
} }
struct file *getfile(int fd) { file *getfile(int fd) {
file *f;
if (fd < 0 || fd >= NOFILE) if (fd < 0 || fd >= NOFILE)
return nullptr; return nullptr;
acquire(&lock_);
return ofile_[fd]; f = ofile_[fd];
// XXX(sbw) f->inc();
release(&lock_);
return f;
} }
int allocfd(struct file *f) { int allocfd(struct file *f) {
for (int fd = 0; fd < NOFILE; fd++){ acquire(&lock_);
for (int fd = 0; fd < NOFILE; fd++) {
if (ofile_[fd] == nullptr){ if (ofile_[fd] == nullptr){
ofile_[fd] = f; ofile_[fd] = f;
release(&lock_);
return fd; return fd;
} }
} }
release(&lock_);
return -1; return -1;
} }
void close(int fd) { void close(int fd) {
struct file *f = ofile_[fd]; struct file *f = ofile_[fd];
acquire(&lock_);
ofile_[fd] = nullptr; ofile_[fd] = nullptr;
release(&lock_);
f->close(); f->close();
} }
...@@ -63,4 +76,5 @@ public: ...@@ -63,4 +76,5 @@ public:
private: private:
struct file *ofile_[NOFILE]; struct file *ofile_[NOFILE];
std::atomic<u64> ref_; std::atomic<u64> ref_;
struct spinlock lock_;
}; };
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论