面试题答案
一键面试在Linux环境下使用C语言开发多线程程序,可以通过pthread_attr_setstacksize
函数来设置线程的栈大小属性。以下是相关函数及参数的使用示例:
- 包含头文件:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
- 设置线程栈大小示例:
#define STACK_SIZE 1024 * 1024 // 1MB栈大小
void* thread_function(void* arg) {
// 线程执行的代码
printf("线程正在运行\n");
return NULL;
}
int main() {
pthread_t thread;
pthread_attr_t attr;
// 初始化线程属性对象
pthread_attr_init(&attr);
// 设置栈大小
pthread_attr_setstacksize(&attr, STACK_SIZE);
// 创建线程
int ret = pthread_create(&thread, &attr, thread_function, NULL);
if (ret != 0) {
perror("pthread_create");
return 1;
}
// 等待线程结束
pthread_join(thread, NULL);
// 销毁线程属性对象
pthread_attr_destroy(&attr);
return 0;
}
在上述代码中:
pthread_attr_init
函数用于初始化线程属性对象attr
。pthread_attr_setstacksize
函数用于设置线程的栈大小,第一个参数为线程属性对象指针,第二个参数为设置的栈大小(以字节为单位)。pthread_create
函数使用设置好栈大小属性的attr
来创建线程。- 最后使用
pthread_attr_destroy
函数销毁线程属性对象。