课程设计-----C语言实现用户态线程

本文详细介绍了如何在不使用pthread库的情况下,使用C语言实现用户态线程,涵盖线程控制流切换、上下文切换、时间片轮转调度等核心功能。通过实际操作,作者在Ubuntu 16.04上完成实验,利用汇编语言进行栈切换,并通过Makefile进行多文件编译。实验过程不仅加深了对线程原理的理解,还涉及了GDB调试、阿里云服务器的使用和Makefile的学习。
摘要由CSDN通过智能技术生成

一、课程设计题目及内容
题目六:C 语言实现用户态线程
内容:在不用操作系统提供的pthread系列函数的情况下,用C语言自行实现用户态线程,包括控制流切换、上下文切换、线程设计和主动切换、时间片轮转调度等功能。
环境:ubuntu 16.04 32位操作系统-----Very import!!!!
方法:在以下资料指导下完成:
访问资料(操作系统基础: C 语言实现用户态线程(实战))

二、程序中使用的数据结构及主要符号说明

struct thread_struct {
   
  int id; //thread_id
  void (*thread_func)();//The function for thread processing
  int esp; // esp(Top of running stack)
  unsigned int wakeuptime; // wakeuptime
  int status; // The status of running
  int counter; //The number of counter
  int priority; // The priority value
  int stack[STACK_SIZE];//Running stack
};

**程序中主要用到的数据结构是线程的结构体thread_struct,线程的结构体中保存了线程中应该有的属性和方法,符号说明如下:

id:用来记录线程的id,即thread_id
thread_func:用来记录线程所用来执行的函数
esp:用来记录程序运行中的栈顶,即栈顶指针
wakeuptime:用来记录线程的唤醒时间,利用当前时间+时间间隔计算得出
status:用来记录线程的运行状态,包括RUNNING,SLEEP,EXIT,READY等
counter:用来记录线程需要占用的时间片
priority:用来记录线程的优先级
stack:线程运行所需要的栈空间**

三、程序流程图

四、带有注释的源程序
1.thread.h,用来定义线程结构体以及一些需要用到的宏变量,以及声明线程函数

#define STACK_SIZE 1024 //Define max size of thread_stack
#define THR_TASKS 32    //Define max size of thread

#define THREAD_STATUS_RUNNING 0//Status:running
#define THREAD_STATUS_SLEEP 1  //Status:sleep
#define THREAD_STATUS_READY 2  //Status:ready
#define THREAD_STATUS_EXIT 3   //Status:exit


struct thread_struct {
   
  int id; //thread_id
  void (*thread_func)();//The function for thread processing
  int esp; // esp(Top of running stack)
  unsigned int wakeuptime; // wakeuptime
  int status; // The status of running
  int counter; //The number of counter
  int priority; // The priority value
  int stack[STACK_SIZE];//Running stack
};

int thread_create(int *tid,void (*start_routine)());
int thread_join(int tid);
void mysleep(int seconds);

2.thread.c,实现线程的相关函数thread_create、thread_join等

#include "thread.h"
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>

static struct thread_struct init_task = {
   0, NULL, THREAD_STATUS_RUNNING, 0, 0, 15, 15, {
   0}};

struct thread_struct *current = &init_task; //Init current thread

struct thread_struct *task[THR_TASKS] = {
   &init_task,}; //Init task list

void schedule();  //Define schedule
void start(struct thread_struct *tsk)
{
   
    tsk->thread_func();   //Run thread
    tsk->status = THREAD_STATUS_EXIT;  //status
    printf("Thread %d excited\n",tsk->id);
    task[tsk->id] = NULL; //Set current position to NULL
    schedule();           //Schedule
}

int thread_create(int *tid, void (*start_routine)()
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值