将结构数据参数传递给线程
Passing struct data arguments to threads
我对如何将结构参数传递给 for 循环中的线程感到困惑。
当我尝试使用这种方法时,我得到了垃圾端口值。当我尝试在没有指针的情况下将 struct
更改为 astruct argstruct;
时,第二个端口会覆盖第一个端口,因此我会打印 200
200
。
此外,我是否必须 free
main
、Func
或两者中的结构?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* Func(void* pstruct);
typedef struct thread_args{
int port;
} astruct;
int main()
{
int peers[2] = {100,200};
pthread_t threads[2];
astruct *argstruct[2];
for (int i = 0; i < 2; i++) {
argstruct[i] = malloc(sizeof(astruct));
argstruct[i]->port = peers[i];
pthread_create(&threads[i],NULL,Func,&argstruct[i]);
}
for(int i = 0; i < 2; i++){
pthread_join(threads[i], NULL);
}
return 0;
}
void* Func(void* pstruct){
int port;
astruct *argstruct = (astruct *)pstruct;
port = argstruct->port;
printf("port: %d\n", port);
return 0;
}
I'm confused on how to pass struct arguments to threads in the for loop.
argstruct[i]
元素是指针,不需要地址运算符:
pthread_create(&threads[i], NULL, Func, argstruct[i]);
请注意,对于这种简单的情况,您不需要内存分配,您可以使用本地数组:
//...
astruct argstruct[2];
for (int i = 0; i < 2; i++) {
argstruct[i].port = peers[i];
pthread_create(&threads[i], NULL, Func, &argstruct[i]);
}
//...
Also, would I have to free
the struct in main, Func, or both?
您应该只释放一次。过程总是一样的,当你不再需要它时,你可以释放它,可以在线程例程中或在 main
.
在您的示例中,您可以很好地释放 port = argstruct->port;
之后的内存,因为在此分配之后您不再使用它:
void* Func(void* pstruct){
int port;
astruct *argstruct = (astruct *)pstruct;
port = argstruct->port;
free(argstruct); //<-- here
printf("port: %d\n", port);
return 0;
}
我对如何将结构参数传递给 for 循环中的线程感到困惑。
当我尝试使用这种方法时,我得到了垃圾端口值。当我尝试在没有指针的情况下将 struct
更改为 astruct argstruct;
时,第二个端口会覆盖第一个端口,因此我会打印 200
200
。
此外,我是否必须 free
main
、Func
或两者中的结构?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* Func(void* pstruct);
typedef struct thread_args{
int port;
} astruct;
int main()
{
int peers[2] = {100,200};
pthread_t threads[2];
astruct *argstruct[2];
for (int i = 0; i < 2; i++) {
argstruct[i] = malloc(sizeof(astruct));
argstruct[i]->port = peers[i];
pthread_create(&threads[i],NULL,Func,&argstruct[i]);
}
for(int i = 0; i < 2; i++){
pthread_join(threads[i], NULL);
}
return 0;
}
void* Func(void* pstruct){
int port;
astruct *argstruct = (astruct *)pstruct;
port = argstruct->port;
printf("port: %d\n", port);
return 0;
}
I'm confused on how to pass struct arguments to threads in the for loop.
argstruct[i]
元素是指针,不需要地址运算符:
pthread_create(&threads[i], NULL, Func, argstruct[i]);
请注意,对于这种简单的情况,您不需要内存分配,您可以使用本地数组:
//...
astruct argstruct[2];
for (int i = 0; i < 2; i++) {
argstruct[i].port = peers[i];
pthread_create(&threads[i], NULL, Func, &argstruct[i]);
}
//...
Also, would I have to
free
the struct in main, Func, or both?
您应该只释放一次。过程总是一样的,当你不再需要它时,你可以释放它,可以在线程例程中或在 main
.
在您的示例中,您可以很好地释放 port = argstruct->port;
之后的内存,因为在此分配之后您不再使用它:
void* Func(void* pstruct){
int port;
astruct *argstruct = (astruct *)pstruct;
port = argstruct->port;
free(argstruct); //<-- here
printf("port: %d\n", port);
return 0;
}