进程转换的例子,用来熟悉汇编和进程转换
; thread_switch.asm
section .data
msg1 db 'thread 1', 0Ah, 0Dh
len1 equ $-msg1
msg2 db 'thread 2', 0Ah, 0Dh
len2 equ $-msg2
section .bss//先定义的在低地址
resb 100 //为什么不是对齐的:因为stack标签在栈底(高地址)
stack1: resb 100
stack2:
sp1: resb 4 //sp记录的是两个线程的栈顶
sp2: resb 4
section .text
global _start
_start:
mov esp, stack1
push thread1 //把函数的地址放到栈里,这样一会esp变成sp的时候,ret之后就跳转过来了
pushad //pushad是把所有的寄存器入栈
mov [sp1], esp
mov esp, stack2 //对线程2进行一模一样的操作
push thread2
pushad
mov [sp2], esp
thread1:
mov esp, [sp1]
mov eax, 4
mov ebx, 1
mov ecx, msg1
call yield
mov edx, len1
int 80h ; print 'thread 1'
mov eax, 1
mov ebx, 0
int 80h ; exit
thread2:
mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, len2
int 80h ; print 'thread 2'
call end_thread ; end thread2, and switch to thread1
yield:
pushad ; save general purpose registers
mov [sp1], esp //记录栈顶,也就是返回地址,一会跳转回来
mov esp, [sp2]
popad ; restore general purpose registers
ret
end_thread:
mov esp, [sp1]
popad
ret