概述
- linux在创建线程时,如果使用默认的栈,默认栈的大小通常为8MB,这对内存比较紧张的嵌入式平台来说,是无法接受的巨量内存浪费;
- pthread_attr_setstack()可以设定线程栈的地址和大小,设定的栈地址必须以linux页面大小对齐,所以这里使用posix_memalign()分配页面对齐的内存;该内存中不使用时也是使用free()释放;
- 线程的最小栈大小为16KB,小于这个数值pthread_attr_setstack会设定失败;
- 在线程中的局部变量是直接从线程栈中分配的,静态局部变量不在线程栈中;所以如果函数调用过多,导致局部变量占用空间超过栈空间,就会引起coredump;
- 如果使用默认栈大小,还可以调用pthread_attr_setguardsize()设定线程栈的溢出保护大小,当栈溢出时,会发SIGSEGV 信号到该线程;
- 如果不想设定线程栈的地址,可以使用pthread_attr_setstacksize来只设定栈大小,让kernel自动分配对应大小的栈,栈最小为16KB,并且是页面(通常为4KB)对齐;这时也可以调用pthread_attr_setguardsize设定栈边界保护区大小(至少为一页),防止爆栈后直接coredump;
pthread_attr_setstack示例
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <sys/prctl.h>
#define DBG_PRINT(fmt, args...) {printf("%s %d ", __FUNCTION__, __LINE__);printf(fmt,##args);}
/**
* [msSleep 用nanosleep实现的毫秒级线程休眠]
* @param msTime [description]
*/
void msSleep(unsigned msTime)
{
struct timespec reqTime;
struct timespec remTime;
int ret = 0;
if(msTime == 0)
{
DBG_PRINT("invalid argument!\n");