C 伪线程三 - 自定义栈地址

5 篇文章 2 订阅

接上文,据我猜测,如果栈可以自己定义地址,每个线程设置不同的栈空间,那么伪线程的局部变量也将是安全的,不会被其他线程覆盖,所以。。。。

测试代码

uint32_t stack[500]; //自定义堆栈地址

int test_fun(int param)
{
	volatile int buff[20] = { 1, 2, 3, 4, 5, 6, 7, 8 };

	return 9;
}

int fn()
{
	__asm {
		mov eax, esp //当前栈位置保存起来
		lea	ebx, [stack + (500-1) * 4] //加载新的栈空间 栈地址是递减的 所以以末尾做开始
		mov esp, ebx //更新栈的地址
		push eax //把旧的栈地址保存起来,出来时需要恢复
		push 56789AB0h //测试压入栈的位置
		call test_fun  //调用函数
		pop ebx //把56789AB0h 弹出来放在ebx中 测试存放地址用
		pop esp //弹出原来的栈地址
	}
	//返回会存放到eax中 
}

int main()
{

	int c = fn();

	printf("fn 返回值 c > %d\r\n", c);

	getchar();

	return c;
}

分析

调试时,stack首地址为0x00EC9540,所以自定义栈的内存范围是

             0x00EC9540-0x00EC9D10         (不包括 0x00EC9D10)

查看内存发现局部变量buff 和传入参数param都在stack中,

 说明重定义栈空间成功了。

 下一步,移入上一章的伪线程中,成败在此一举

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C语言多线程计算30000000-30001000之间的质数的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 4 #define RANGE_START 30000000 #define RANGE_END 30001000 // 定义线程参数结构体 typedef struct { int start; int end; int *count; } thread_args; // 判断一个数是否为质数 int is_prime(int num) { int i; if (num <= 1) { return 0; } for (i = 2; i*i <= num; i++) { if (num % i == 0) { return 0; } } return 1; } // 线程函数 void *thread_func(void *args) { int i, count = 0; thread_args *thread_args = (thread_args *)args; for (i = thread_args->start; i <= thread_args->end; i++) { if (is_prime(i)) { count++; } } *(thread_args->count) += count; pthread_exit(NULL); } int main() { int i, count = 0; pthread_t threads[NUM_THREADS]; thread_args args[NUM_THREADS]; // 分配线程任务 for (i = 0; i < NUM_THREADS; i++) { args[i].start = RANGE_START + i*(RANGE_END-RANGE_START)/NUM_THREADS; args[i].end = RANGE_START + (i+1)*(RANGE_END-RANGE_START)/NUM_THREADS - 1; args[i].count = &count; pthread_create(&threads[i], NULL, thread_func, (void *)&args[i]); } // 等待线程结束 for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("Number of primes between %d and %d is %d\n", RANGE_START, RANGE_END, count); return 0; } ``` 代码中使用了4个线程来计算,可以根据需要调整`NUM_THREADS`的值。线程函数`thread_func`中计算每个线程分配到的范围内的质数数量,并将结果累加到`count`变量中。最终输出计算结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值