【发布时间】:2016-09-02 21:10:49
【问题描述】:
所以我有一个多线程 C 程序,将在其中创建 N 个 pthread。我必须通过结构给线程一些参数。为了不必分配 N 结构,检查是否没有 malloc 错误,通过引用将它们传递给我的线程,然后释放结构数组,我想简单地创建一个临时结构和按值传递。这是一个演示问题的简单代码:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
struct thread_arg {
int value1;
char value2;
float value3;
};
void *foo(void *arg);
int main(int argc, char *argv[])
{
int N = atoi(argv[1]);
pthread_t *thread = (pthread_t *) malloc(N * sizeof(pthread_t));
for (int i = 0; i < N; i++) {
struct thread_arg arg;
arg.value1 = i;
arg.value2 = 'f';
arg.value3 = i / 10;
pthread_create(&thread[i], NULL, foo, arg);
}
free(thread);
pthread_exit(NULL);
}
void *foo(void *arg)
{
struct thread_arg my_arg = (struct thread_arg) arg;
printf("%d%c%f\n", my_arg.value1, my_arg.value2, my_arg.value3);
return NULL;
}
我知道将结构按值传递给期望它的函数是完全正常的,但是对于线程及其 NULL 指针,无论我进行何种类型的强制转换,我都会遇到错误。
【问题讨论】:
-
“你不能”可能是答案
-
如果您要解决的问题需要创建多个线程,那么 malloc 结构并检查 malloc 是否失败并不是很大的成本。
-
请注意,发布的代码有问题,因为有可能(确实很可能)当 foo() 函数在子线程中执行时,“arg”结构将不再存在于主线程的堆栈。 (正如其他人所说,修复是动态分配结构;这样线程可以通过在使用完成时释放它来控制结构的生命周期)
-
在未先检查
argc以确保命令行参数确实存在之前,请勿引用argv[0]之外的内容。 -
谢谢你们所有的cmets!
标签: c multithreading pthreads