linux内部pthread_create函数创建设置栈大小方法

pthread_create函数是Unix/Linux下创建线程的函数,它的原型如下:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);

其中,pthread_attr_t是用来设置线程属性的,它可以设置线程的栈的大小。但是,需要注意的是,pthread_attr_t结构体中并没有直接提供设置栈大小的属性。

pthread_create 创建线程时,若不指定分配堆栈大小,系统会分配默认值,查看默认值方法如下

# ulimit -s

8192

#

上述表示为8M;单位为KB。

也可以通过# ulimit -a 其中 stack size 项也表示堆栈大小。ulimit -s  value 用来重新设置stack 大小。

一般来说 默认堆栈大小为 8388608; 堆栈最小为 16384 。 单位为字节。

堆栈最小值定义为 PTHREAD_STACK_MIN ,包含#include <limits.h>后可以通过打印其值查看。对于默认值可以通过pthread_attr_getstacksize (&attr, &stack_size); 打印stack_size来查看。

尤其在嵌入式中内存不是很大,若采用默认值的话,会导致出现问题,若内存不足,则 pthread_create 会返回 12,定义如下:

#define EAGAIN 11
 
#define ENOMEM 12 /* Out of memory */

在Linux下,我们可以使用pthread_attr_setstacksize函数来设置新线程的栈大小。

下面是一个简单的例子:

#include <pthread.h>
#include <stdio.h>

void* thread_start(void* arg) {
    printf("New thread stack size: %ld\n", pthread_get_stacksize_np(pthread_self()));
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    // 设置新线程的栈大小
    size_t stack_size = 1024 * 1024; // 1MB
    pthread_attr_setstacksize(&attr, stack_size);

    // 创建线程
    pthread_create(&thread, &attr, &thread_start, NULL);

    // 等待线程结束
    pthread_join(thread, NULL);

    pthread_attr_destroy(&attr);
    return 0;
}

在这个例子中,我们创建了一个新的线程,并且设置了它的栈大小为1MB。在线程的入口函数中,我们通过pthread_get_stacksize_np函数来获取并打印出新线程的栈大小。

需要注意的是,pthread_get_stacksize_np函数是非标准的,它在GNU libc下可用,但在其他的实现中可能不可用。

另外,设置线程栈的大小应该在创建线程之前进行,一旦线程运行起来,尝试改变栈的大小可能会失败或者引发不可预知的结果。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pthread_create函数Linux下用于创建线程的函数。它的原型如下: ```c #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` 该函数的参数解释如下: - thread:指向pthread_t类型的指针,用于存储新创建线程的ID。 - attr:指向pthread_attr_t类型的指针,用于设置线程的属性。如果传入NULL,则使用默认属性。 - start_routine:指向一个函数的指针,该函数是新线程的起始函数。新线程将从该函数开始执行。 - arg:传递给start_routine函数的参数。 该函数的返回值为整型,表示函数执行的结果。如果成功创建线程,则返回0;如果出现错误,则返回一个错误号。 下面是一个使用pthread_create函数创建线程的示例: ```c #include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { int *num = (int *)arg; printf("This is a new thread. The argument is %d\n", *num); pthread_exit(NULL); } int main() { pthread_t thread; int num = 10; int ret = pthread_create(&thread, NULL, thread_func, &num); if (ret != 0) { printf("Failed to create thread\n"); return 1; } printf("Main thread\n"); pthread_join(thread, NULL); return 0; } ``` 该示例中,我们定义了一个新线程的起始函数thread_func,该函数接收一个整型参数,并在新线程中打印该参数的值。在主线程中,我们使用pthread_create函数创建了一个新线程,并将参数传递给新线程。然后,主线程继续执行自己的代码,最后使用pthread_join函数等待新线程的结束。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值