&引用';X`可能在此函数中未初始化";警告和pthread,C

&引用';X`可能在此函数中未初始化";警告和pthread,C,c,pthreads,warnings,C,Pthreads,Warnings,下面的代码产生以下警告: “factoryThread”可在未初始化的情况下在此函数中使用[-Wmaybe uninitialized] pthread\u t factoryThreads[NUM\u FACTORIES]; int factoryNums[NUM_FACTORIES]; 对于(int i=0;i

下面的代码产生以下警告:

“factoryThread”可在未初始化的情况下在此函数中使用[-Wmaybe uninitialized]

pthread\u t factoryThreads[NUM\u FACTORIES];
int factoryNums[NUM_FACTORIES];
对于(int i=0;i
代码似乎按预期工作,但我仍然很好奇是什么导致了警告,以及我能做些什么来修复它。

您通过使用具有自动存储持续时间(不确定)的未初始化变量的值调用了未定义的行为,它恰好工作

删除无意义的变量和赋值

pthread_t factoryThreads[NUM_FACTORIES];
int factoryNums[NUM_FACTORIES];
for (int i = 0; i < NUM_FACTORIES; i++) {
    factoryNums[i] = i + 1;
    pthread_create(&factoryThreads[i], NULL, createAndInsertCandy,
            &factoryNums[i]);
}
pthread\u t factoryThreads[NUM\u FACTORIES];
int factoryNums[NUM_FACTORIES];
对于(int i=0;i
pthread\u t factoryThread;factoryThreads[i]=factoryThread;什么是“自动存储持续时间”?您的意思是,当创建它的函数返回时,它会超出范围吗?该代码在我的
main()
函数中,因此线程在程序结束之前不会超出范围。是否仍然存在问题(出厂线程在
main()
完成之前全部完成)?否,
factoryThread
是块中的局部变量,退出
for
循环后它将消失。本例中的问题不是它们消失了,而是未初始化的非静态局部变量具有不确定的变量,并且您使用了它,这是错误的。然后,修订后的代码中的
factoryThread
对象可能在
pthread_create()
内初始化?这可能超出了注释部分的范围,但是你认为我应该把
pthread\u create()
放在if块中检查创建是否成功吗?更一般地说,使用POSIX线程需要调用相当多的
pthread.
函数。它们是否都应该嵌入到if块中?
pthread_t factoryThreads[NUM_FACTORIES];
int factoryNums[NUM_FACTORIES];
for (int i = 0; i < NUM_FACTORIES; i++) {
    factoryNums[i] = i + 1;
    pthread_create(&factoryThreads[i], NULL, createAndInsertCandy,
            &factoryNums[i]);
}