我正在从 main 函数创建一个线程 A,该线程又会生成另一个子线程 B。我想使用 pthread_attr_setstacksize()
将堆栈大小显式分配给线程 A 和 B。
根据需求,父线程A的栈大小小于子线程B。
我很困惑,如果子线程的栈是从父线程的栈空间分配的,或者父子线程的栈空间完全不同。
谁能帮帮我?
最佳答案
I want to explicitly assign the stack size to threads A and B using pthread_attr_setstacksize().
所以,你这样做:
pthread_attr_t attrs;
pthread_t A, B;
void *A_retval, *B_retval;
int result;
result = pthread_attr_init(&attrs);
if (result) {
fprintf(stderr, "Cannot initialize thread attributes: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
result = pthread_attr_setstacksize(&attrs, A_STACK_SIZE);
if (result) {
fprintf(stderr, "Cannot set stack size %zu for thread A: %s.\n", (size_t)A_STACK_SIZE, strerror(result));
exit(EXIT_FAILURE);
}
result = pthread_create(&A, &attrs, A_FUNCTION, NULL);
if (result) {
fprintf(stderr, "Cannot create thread A: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
result = pthread_attr_setstacksize(&attrs, B_STACK_SIZE);
if (result) {
fprintf(stderr, "Cannot set stack size %zu for thread B: %s.\n", (size_t)A_STACK_SIZE, strerror(result));
exit(EXIT_FAILURE);
}
result = pthread_create(&B, &attrs, B_FUNCTION, NULL);
if (result) {
fprintf(stderr, "Cannot create thread A: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
pthread_attr_destroy(&attrs);
/* TODO: Perhaps this thread also does something? */
/* Wait for A and B to exit. */
result = pthread_join(A, &A_retval);
if (result)
fprintf(stderr, "Warning: Thread A: %s.\n", strerror(result));
result = pthread_join(B, &B_retval);
if (result)
fprintf(stderr, "Warning: Thread B: %s.\n", strerror(result));
As per the requirement, the stack size of parent thread A is smaller than the child thread B.
只要确保大小是页面大小 (sysconf(_SC_PAGESIZE)
) 的倍数,并且至少是 PTHREAD_STACK_MIN
。
没有父线程或子线程。他们都是“ sibling ”,属于同一个进程。有一个“主线程”,它是进程启动时的唯一线程,但它没有任何特殊之处。它的名字来自 main()
,因为它是开始运行该函数的线程。哪个线程创建了其他线程根本无关紧要。
如果在某些代码中提到了线程之间的父子关系,那么它用于反射(reflect)代码的逻辑,而不是线程的实际关系。 “Parent” 和“child” 只是“创建新线程的线程” 和“新线程”的简写创建线程”。
进程确实有真正的父子关系——例如,只有一个父进程可以获取它的子进程——但在 Linux 中,所有线程都是一个进程中的兄弟:任何线程都可以加入/获取同一进程中的任何其他线程.
I am confused that if the stack of a child thread is allocated from stack space of parent thread or the stack space of parent and child thread are completely different.
不,每个线程都有自己独立的堆栈。这个新堆栈几乎总是由 pthread_create()
调用自动分配和准备,如果指定了属性,则使用所需的堆栈大小,如果没有指定属性,则使用默认堆栈大小(很大,几兆字节)指定。
(有一个 pthread_attr_setstack()
调用,用于为使用该组属性创建的下一个线程设置显式堆栈。一些非常古怪的应用程序可能需要特定的堆栈安排。堆栈区域不是只是一些随机的内存块;它确实需要正确对齐,足够大,等等。例如,可以使用 mmap()
自己分配它,但这绝对不是你的事情应该永远需要或想要做。)
查看程序本身或某些特定进程使用的内存区域可能很有趣或提供信息。
在 Linux 中,您的程序可以打开并读取 /proc/self/maps
伪文件(它不是磁盘上的真实文件,而是内核在运行时动态生成的类文件实体您打开并阅读它),或者您可以阅读与进程 ID PID
对应的任何 /proc/PID/maps
。
每行的前两个十六进制数描述地址范围,堆栈标记为[stack]
。
参见 man 5 proc
有关 /proc
伪文件系统中文件的更多信息。
关于c - 子线程的栈空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37855615/