我在 pthreads 中制作了一个简单的程序,它通过一个结构将多个参数传递给被调用的函数。考虑这两个程序:
程序 1:
#include <pthread.h>
#include <stdio.h>
#include <malloc.h>
struct args{
long long val1;
int val2;
};
void *hello(void* threadid){
struct args *tid;
tid=(struct args*)threadid;
printf("thread %lld\n",tid->val1);
pthread_exit(NULL);
}
int main(){
pthread_t threads[20];
int i;
for(i=0;i<20;i++){
// ***** specific memory given to the struct *****
struct args* a1=(struct args*)malloc(sizeof(struct args));
a1->val1=i;
a1->val2=i+1;
int ret=pthread_create(&threads[i],NULL,hello,(void*)a1);
if(ret){
printf("error code %d for %d\n",ret,i);
}
}
pthread_exit(NULL);
}
它按预期打印输出,一些排列0..19
另一方面,考虑程序 p2
#include <pthread.h>
#include <stdio.h>
struct args{
long long val1;
int val2;
};
void *hello(void* threadid){
struct args *tid;
tid=(struct args*)threadid;
printf("thread %lld\n",tid->val1);
pthread_exit(NULL);
}
int main(){
pthread_t threads[20];
int i;
for(i=0;i<20;i++){
// ***** struct made like normal declarations *****
struct args a1;
a1.val1=i;
a1.val2=i+1;
int ret=pthread_create(&threads[i],NULL,hello,(void*)&a1);
if(ret){
printf("error code %d for %d\n",ret,i);
}
}
pthread_exit(NULL);
}
这个程序有重复和不完整的条目,比如
thread 3
thread 5
thread 3
thread 4
thread 3
thread 6
thread 7
thread 8
thread 9
thread 10
thread 11
thread 12
thread 13
thread 15
thread 15
thread 16
thread 17
thread 18
thread 19
thread 19
为什么结构的实例化直接导致这种重叠?C不应该为循环中的每次提供一个新的内存块吗?