我一直在拼命地尝试将一个结构传递给多个线程。问题是我找不到在 pthread_create 函数中传递它的正确格式。它只是行不通。 如果试图将我的结构指针传递给 pthread_create 但它不会起作用。 我有指针赋值错误。
typedef struct thread{
pthread_t thread_id;
char *filename;
int blocksize;
int random_int;
} ThreadData;
int main(int argc, char *argv[]) {
int nb_threads = atoi(argv[3]);
int blocksize = atoi(argv[2]);
int re;
int index;
char *name;
char* mode = argv[1];
int i = 0;
ThreadData thread[nb_threads];
int random_int;
srand(time(NULL));
random_int = rand();
index = detect_mode(mode);
index_glob = index;
for(i=0; i < nb_threads; i++){
snprintf(name, 25,"temp%d",i);
thread[i].filename = name;
thread[i].blocksize = blocksize;
thread[i].random_int = random_int;
switch(index_glob){
case 0:
re = pthread_create(&(thread[i].thread_id),NULL,write_seq_file,(void *)(&thread[i]));
break;
case 1:
re = pthread_create(&(thread[i].thread_id),NULL,write_ran_file,(void *)(&thread[i]));
break;
case 2:
re = pthread_create(&(thread[i].thread_id),NULL,read_seq_file,(void *)(&thread[i]));
break;
case 3:
re = pthread_create(&(thread[i].thread_id),NULL,read_ran_file,(void *)(&thread[i]));
break;
default:
exit(0);
break;
}
if(re == -1){
printf("Error creating thread %d / %d\n",(i+1),nb_threads);
}
else{
printf("Thread %d / %d created.\n",(i+1),nb_threads);
}
}
for(i=0; i< nb_threads; i++){
pthread_join(thread[i].thread_id, NULL);
}
return 0;
}
void* write_seq_file(void *thread){
ThreadData *my_data = (ThreadData*)thread;
char *filename = my_data->filename;
FILE* fp = fopen(filename,"w+");
int blocksize = my_data->blocksize;
char c = 'a';
long i;
for (i=0; i<blocksize; i++){
fputc(c,fp);
}
pthread_exit(NULL);
}
最佳答案
我不太了解你的程序,我不确定它是否会按你期望的那样运行。 但是;
这里有几点可以让它编译:
pthread_create 需要一个 void *(*start_routine) (void *) 作为辅助函数。因此,将 write_seq_file 和所有辅助函数更改为以下格式。
void* write_seq(void *thread)
{
...
return NULL;
}
您的 Thread 数据数组是一个对象数组。不是指针。因此,首先获取地址并将其转换为 void。
re = pthread_create(&(thread[i].thread_id),NULL,write_seq_file,(void *)(&(thread[i])));
不确定中间的 exit(0) 是否是个好主意。我宁愿使用 return 0;因为主函数必须返回一个值。
以下未在给定代码中声明。所以希望那里没有问题。
index = detect_mode(mode);
index_glob = index;
确保在 main 之前声明了函数原型(prototype),或者将函数实现移到 main 函数之上。
最后,pthread_join 需要一个 pthread_t 线程作为第一个参数。该行应如下所示进行更改。
pthread_join(thread[i].thread_id, NULL);
希望这对您有所帮助。
关于c - 将带有数组的结构传递给多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25968171/