LPTHREADS:指向结构体的指针还是结构体地址?多进程多线程传参咨询
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_tstruct usingmalloc(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]topthread_create, you're giving each thread a pointer to its dedicated struct. The thread function can safely cast thisvoid*back tothread_args_t*and accesschild_id/thread_idwithout 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 athread_args_tstruct: It's a variable that stores the memory address of the struct you allocated withmalloc.- The "struct's address" is exactly the value held in that pointer. When you pass
thread_arg[i]topthread_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

