C线程变量在从其他线程声明后具有值

Pro*_*kop 1 c multithreading pthreads thread-safety

我想用C做一些简单的事情,我很困惑.程序很简单,主要功能是根据作业que结构处理线程.它一次打开4个线程.大约300个线程直到最后.线程函数始终相同但args不同.

这里的孔代码有点长,所以我会粘贴一些零件.

线程正如以下参数一样打开:
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
pthread_create(&pth, &attr, dothejob, (void *) varis);
Run Code Online (Sandbox Code Playgroud) 线程称为函数
void *dothejob(void * varis){
unsigned char * arr1;
arr1 = (unsigned char*) calloc(3000000, sizeof (unsigned char));
unsigned char * arr2;
arr2 = (unsigned char*) calloc(3000000, sizeof (unsigned char));
// doing some calculations and comparisons and stuff
unsigned int topten[10];  
// <---- here topten has some values from previous threads, but why ? 
// picking top ten and putting it in the var topten[
free(arr1);
free(arr2);
pthread_detach(pthread_self());
}
Run Code Online (Sandbox Code Playgroud) 如果有人知道,请帮助我.先感谢您.

Pau*_*aul 5

当你在函数内写这个:

unsigned int topten[10];  
Run Code Online (Sandbox Code Playgroud)

数组值未初始化为0.它们包含在位置topten点的内存中发生的任何事情.使用topten数组中的值而不首先将自己的新值写入数组是未定义的行为.如果你想用你的数组填充0s,你应该像这样初始化它:

unsigned int topten[10] = {0};
Run Code Online (Sandbox Code Playgroud)

  • @Prokop在第一个帖子中填充"0"的事实纯属巧合.那就是记忆中发生的事情.但它并没有"初始化"为"0".你不能像这样使用未初始化的值.如果要将数组初始化为"0",可以这样做:`unsigned int topten [10] = {0};` (3认同)