当前位置:网站首页>A user level thread library based on C language
A user level thread library based on C language
2022-06-29 16:56:00 【biyezuopinvip】
Resource download address :https://download.csdn.net/download/sheziqiong/85821835
Resource download address :https://download.csdn.net/download/sheziqiong/85821835
Implementation of user level thread library
One 、 Specific contents of thread library
Before using the thread library, you must first call uthread_init(). This function is executed only once , Responsible for initializing the data structure , For example, the overall situation uthreads Matrix and ut_curthr( Currently executing thread ). uthread_init() There are some special codes in , Handle the context of the currently executing process ( That is to call uthread_init() The process of ), Make it an effective uthread, And set up ut_curthr For the sake of uthread, This uthread Called the main thread or 0 Number thread . After everything is initialized , You can use threads uthread_create() Create thread .
Once the thread is created , The thread library can schedule these threads . If the thread needs to be temporary yield The processor gives another thread ( Still executable , That is, it is in the ready state ), You need to call uthread_yield(). Threads can pass through uthread_block() Go to sleep , It can also be done through uthread_wake() Awakened .uthread_switch() The function is responsible for selecting another thread to run . Scheduler scheduling , Priority scheduling algorithm is adopted , Thread priority can be determined by uthread_setprio() Set up , The larger the number, the higher the priority , Threads of the same priority take turns CPU. One queue per priority , For relevant data structures, see uthread_sched.c Medium runq_table.
Uthreads The threads in are 6 States , The definition is as follows :
typedefenum{
UT_NO_STATE,/* Invalid thread state */
UT_ON_CPU,/* Thread is executing */
UT_RUNNABLE,/* Threads can run , be ready */
UT_WAIT,/* Thread blocked */
UT_ZOMBIE,/* Threads in the zombie state , It's over , But we need to recycle resources */
UT_TRANSITION,/* Thread in creation state */
UT_JOINABLE,// When a thread ends, it needs a thread to reclaim its resources
UT_DETACHABLE,// At the end of the thread , No need for a thread to reclaim its resources
UT_NUM_THREAD_STATES// Number of thread states
} uthread_state_t;
stay uthreads There will never be more than one thread executing at the same time , But threads can be preempted . stay uthreads in , Use uthread_makecontext() Create the machine context of the thread . If you need to change the thread currently executing , Need to call uthread_swapcontext(), This makes the current CPU The context is saved , The new context is executed . Save the context as newctx Parameter is called after uthread_swapcontext() Is re executed .
Uthread There is a thread in that is called Reaper Threads , That is to say 1 Number thread , Responsible for cleaning up the resources occupied by the ended thread . It is worth noting that reaper Not that the cleanup is over but not yet joined Of non-detached Threads , Rather let uthread_join() To complete .
Two 、 Implementation process
The functions to be implemented are as follows ( For more specific implementation ideas, please see the comments of the source code ).
uthread_yield: The currently running thread gives up CPU, The thread is still runnable , namely UT_RUNNABLE. When this function is called , The current thread is added to the ready queue , If the current thread is larger than the highest priority thread in the system , Directly from uthread_yield return ; Otherwise give up CPU, Switch to the highest priority thread .
uthread_wake: Wake up the specified thread , Make it executable again ( Be careful : The thread may already be in a ready state ). What has been done : Change state , Put it in the ready queue .
uthread_setprio: Change the priority of the specified thread . Be careful , If the thread is already in UT_RUNNABLE state ( Executable , But no possession CPU), The priority queue should be changed , If the specified thread has a higher priority than the current caller , Then the caller has to give up CPU; If the thread status is UT_TRANSITION, Then it is a newly created thread ( About to be put into the ready queue for the first time ), Change its status to UT_RUNNABLE. Return on success 1, Otherwise return to 0.
uthread_switch: Find the highest priority runnable thread , And then use uthread_swapcontext() Switch to it ( Pay attention to the settings UT_ON_CPU Thread state and current thread ). If the calling thread itself is the highest priority thread , Then switch the callback thread . Main work : Find the thread with the highest priority in the system , And switch ( There must be an executable thread ).
uthread_init: This function is called only once when the user process starts , Used to initialize all global data structures and variables . This function needs to set the of each thread ut_state and ut_id, Simplicity , The system selects the subscript of the thread array as ut_id.
uthread_create: Create a thread to execute the specified function , The arguments to the function are and , The priority for . First , Use uthread_alloc Find a valid id, Can't find the , Return the appropriate error ; then , Assign a stack to a thread , An appropriate error is returned when the allocation is unsuccessful ; Use uthread_makecontext() Create thread context ; According to the newly discovered thread id, Set up uthread_t structure , call uthread_setprio Set the priority of the thread , Return thread in id. If unsuccessful, return 0.
uthread_exit: End the current thread ( Pay attention to the settings uthread_t The logo in ). If the thread is UT_DETACHABLE, By calling make_reapable() Put it in the cleanup thread (reaper) Clean up the queue and wake up the cleanup thread . If the thread is UT_JOINABLE, Then wake up the waiting thread . And then call uthread_switch() Switching thread .
uthread_join: Wait for the specified thread to end , If the thread does not end execution , The calling thread needs to be blocked , Until the thread ends . Main work : If the waiting thread has not finished , Then set the waiting thread of the thread as the current thread , The thread state is changed to UT_WAIT, Switching thread ; If you successfully wait until the thread ends , Call make_reapable Wake up the cleanup thread reaper Clean it thoroughly . Error condition and corresponding error code Reference resources pthread_join Of manpage.
uthread_self: Returns the of the currently executing thread id.
uthread_alloc: Find a free uthread_t, Back to its id(uthread_id_t).
uthread_destroy: Clean up the specified thread .
uthread_cond_init: Initializes the specified condition variable .
uthread_cond_wait: Wait for the specified condition variable . Change the state of the current thread , Release the lock held by the current thread , And put the current thread into the waiting queue of the condition variable , Switching thread .
uthread_cond_broadcast: Wake up all threads waiting for this condition variable .
uthread_cond_signal: Wake up a thread waiting for this condition variable .
uthread_mtx_init: Initializes the specified mutex.
uthread_mtx_lock: If no thread owns the lock , Change the lock owner to the current thread , otherwise , Currently blocked , Give up CPU.
uthread_mtx_trylock: Attempt to lock mutex, Returns when a lock is obtained 1, Otherwise return to 0.
uthread_mtx_unlock: Release the lock . If there are other threads waiting for the lock , Then wake it up .
3、 ... and 、 Result analysis
Resource download address :https://download.csdn.net/download/sheziqiong/85821835
Resource download address :https://download.csdn.net/download/sheziqiong/85821835
边栏推荐
- 稳定币风险状况:USDT 和 USDC 安全吗?
- 适合中小企业的项目管理系统有哪些?
- Stable currency risk profile: are usdt and usdc safe?
- Perhaps in two years, ASML will be free to supply EUV lithography machines to China
- Tool chain empowers hundreds of companies, horizon opens the "Matthew effect" of mass production of intelligent driving
- After 3 years of testing experience, do you know the state transition method for use case design?
- Redis布隆过滤器和布谷鸟过滤器
- 机器学习8-人工神经网络
- 知道创宇为能源行业资产管理助力,入选工信部2021物联网示范项目
- 卷妹带你学数据库---5天冲刺Day1
猜你喜欢
美国芯片再遭重击,Intel或将被台积电击败而沦落至全球第三
深圳内推 | 深圳计算科学研究院招聘机器学习助理工程师(校招)
机器学习7-支持向量机
Which version of JVM is the fastest?
A tour of gRPC:02 - 从proto生成代码
我的远程办公初体验 | 社区征文
或许再过两年,ASML将可以自由给中国供应EUV光刻机
函数计算异步任务能力介绍 - 任务触发去重
C winfrom chart chart control bar chart and line chart
Comprehensive analysis of Seata distributed transaction at and XA
随机推荐
Real test = "half product + Half development"?
C语言微博用户管理系统
curl: (56) Recv failure: Connection reset by peer
New feature of C11 - Auto and decltype type type indicators
In order to prevent being rectified after 00, a company requires employees not to sue the company
穩定幣風險狀况:USDT 和 USDC 安全嗎?
STM32按键消抖——入门状态机思维
数学知识:求组合数 II—求组合数
如何利用OpenMesh实现不同格式的3D文件间的转换
Top the list for 10 consecutive years? What is the "most common" programming language for programmers?
MySQL foundation - multi table query
Telnet+ftp to control and upgrade the equipment
把这份关于软件测试一系列笔记研究完,进大厂是个“加分项”...
Implement a ThreadLocal by yourself
分片信息调哪个参数呢?用的是MySQLsource stream api,不是table api
535. TinyURL 的加密与解密 / 剑指 Offer II 103. 最少的硬币数目
How to use openmesh to realize the conversion between 3D files of different formats
Why does selenium become the first choice for web automated testing? (source code attached)
基于汇编实现的流载体的LSB隐藏项目
redolog和binlog