You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LPTHREADS:指向结构体的指针还是结构体地址?多进程多线程传参咨询

Thread Creation & pthread_create Argument Clarification

Hey Roberto, great question! Let's break this down step by step:

1. Why Your Current Code Works Correctly

Your approach to spawning threads is solid, and here's why it runs smoothly:

  • You're allocating independent heap memory for each thread_args_t struct using malloc(sizeof(thread_args_t)) inside the loop. This means every thread gets its own unique struct instance—no race conditions or overwritten data between threads.
  • When you pass thread_arg[i] to pthread_create, you're giving each thread a pointer to its dedicated struct. The thread function can safely cast this void* back to thread_args_t* and access child_id/thread_id without worrying about other threads modifying the same data.

Quick reminder: Don't forget to free this heap memory once threads finish processing (either inside the thread function or after joining all threads) to avoid memory leaks!

2. Clarification: Pointer to Struct vs. Struct Address in pthread_create

Let's clear up the confusion—these two terms describe the same thing, just from different angles:

  • thread_arg[i] is a pointer to a thread_args_t struct: It's a variable that stores the memory address of the struct you allocated with malloc.
  • The "struct's address" is exactly the value held in that pointer. When you pass thread_arg[i] to pthread_create, you're passing the starting memory address of the struct (since the pointer itself contains that address).

To put it plainly: The fourth argument of pthread_create accepts a void* (generic pointer) that holds the memory location of your data. Your thread_arg[i] fits perfectly here because it's a pointer containing the struct's address. The thread function will usually cast this back to your struct type to access members, like this:

void* thread_function(void* arg) {
    thread_args_t* args = (thread_args_t*)arg;
    // Use args->child_id and args->thread_id safely here
    return NULL;
}

As a side note: If you used a stack-allocated struct (e.g., thread_args_t stack_arg;), you'd pass &stack_arg (the struct's address) to pthread_create—which is also a pointer to the struct, just pointing to stack memory instead of heap. The catch here is stack memory can be reclaimed or modified by the parent thread before the child uses it, which is why your heap-based approach is safer for this use case.


内容的提问来源于stack exchange,提问作者Roberto Aureli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:18:22