Skip to content

Commit

Permalink
misc: Refcount thread handles
Browse files Browse the repository at this point in the history
  • Loading branch information
Qwinci committed Oct 30, 2023
1 parent 4dc5247 commit da40ac8
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@

ACTIVE_INPUT_TASK = test_user;
ThreadHandle* h = kmalloc(sizeof(ThreadHandle));
h->refcount = 1;
h->task = test_user;
h->exited = false;
memset(&h->lock, 0, sizeof(Mutex));
Expand Down
7 changes: 6 additions & 1 deletion src/sched/process.c
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,13 @@ void process_destroy(Process* process) {

switch (type) {
case HANDLE_TYPE_THREAD:
kfree(data, sizeof(ThreadHandle));
{
ThreadHandle* h = (ThreadHandle*) data;
if (--h->refcount == 0) {
kfree(data, sizeof(ThreadHandle));
}
break;
}
case HANDLE_TYPE_DEVICE:
((GenericDevice*) data)->refcount -= 1;
break;
Expand Down
3 changes: 2 additions & 1 deletion src/sched/task.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ typedef struct {
Task* task;
int status;
};
bool exited;
Mutex lock;
usize refcount;
bool exited;
} ThreadHandle;

typedef struct {
Expand Down
8 changes: 7 additions & 1 deletion src/sys/syscalls.c
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ Handle sys_create_thread(void (*fn)(void*), void* arg) {
mutex_unlock(&process->threads_lock);
return INVALID_HANDLE;
}
handle->refcount = 1;

Task* task = arch_create_user_task(self->process, "user thread", fn, arg);
if (!task) {
Expand Down Expand Up @@ -433,8 +434,13 @@ int sys_close(Handle handle) {
if (handle_tab_close(&arch_get_cur_task()->process->handle_table, handle)) {
switch (type) {
case HANDLE_TYPE_THREAD:
kfree(data, sizeof(ThreadHandle));
{
ThreadHandle* h = (ThreadHandle*) data;
if (--h->refcount == 0) {
kfree(data, sizeof(ThreadHandle));
}
break;
}
case HANDLE_TYPE_DEVICE:
((GenericDevice*) data)->refcount -= 1;
break;
Expand Down
9 changes: 7 additions & 2 deletions src/utils/handle.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "sys/dev.h"
#include "fs/vfs.h"
#include "sys/fs.h"
#include "sched/task.h"

Handle handle_tab_insert(HandleTable* self, void* data, HandleType type) {
mutex_lock(&self->lock);
Expand Down Expand Up @@ -131,9 +132,13 @@ bool handle_tab_duplicate(HandleTable* self, HandleTable* ret) {

switch (type) {
case HANDLE_TYPE_THREAD:
//kfree(data, sizeof(ThreadHandle));
// todo refcount
{
ThreadHandle* h = (ThreadHandle*) data;
if (--h->refcount == 0) {
kfree(data, sizeof(ThreadHandle));
}
break;
}
case HANDLE_TYPE_DEVICE:
((GenericDevice*) data)->refcount += 1;
break;
Expand Down

0 comments on commit da40ac8

Please sign in to comment.