gpt4 book ai didi

c - C中的段错误执行并发服务器

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:34 25 4
gpt4 key购买 nike

我正在做一个并发服务器,我有一个进程,其功能是加入关闭的线程。问题是在他检查线程是否工作时我遇到了段错误。

这里我把status初始化为2,表示还没有执行。然后我执行线程

for (int i = 0; i < Max_threads; i++){
clients_data[i].client_number = 0;
clients_data[i].status = 2;
}
pthread_create(&tjoins, NULL, (void *(*) (void *))process_joins, (void*)&clients_data);

这是函数:

void* process_joins(struct clients* data[Max_threads]){     
while (true){
for (int i = 0; i < Max_threads; i++){
if(data[i]->status == 0){
pthread_join(tclient[data[i]->position], (void**)&data[i]->info);
data[i]->client_number = 0;
}

}
}
return 0;

在执行 printf 以检查代码在哪里中断时,我知道它发生在以下行:

if(data[i]->status==0){

提前谢谢你。

最佳答案

我假设您已将 clients_data 声明为 -

struct clients clients_data[Max_threads];

您正在将 &clients_data 传递给类型为 struct clients (*)[Max_threads] 的函数。但是该函数期望的是 struct clients* [Max_threads]。这些都是不同的东西。

要解决此问题,您可以将函数定义更改为 -

void* process_joins(struct clients (*data)[Max_threads]){
while (true){
for (int i = 0; i < Max_threads; i++){
if((*data)[i].status == 0){
pthread_join(tclient[(*data)[i].position], (void**) &((*data)[i].info));
(*data)[i].client_number = 0;
}
}
}
}

但是因为这个函数应该期待一个void*,我建议使用

void *process_joins(void *data_ptr) {
struct clients (*data)[Max_threads] = data_ptr;
// Rest of the function same as above
}

现在,虽然这可以解决您的问题,但您实际上并不需要指向数组的指针,您可以将指向第一个元素的指针传递为 -

pthread_create(&tjoins, NULL, (void *(*) (void *))process_joins, (void*)clients_data);

并将您的函数定义为 -

void* process_joins(void *clients_data_ptr){
struct clients *data = clients_data_ptr;
while (true){
for (int i = 0; i < Max_threads; i++){
if((data[i].status == 0){
pthread_join(tclient[data[i].position], (void**) &(data[i].info));
data[i].client_number = 0;
}

}
}
}

关于c - C中的段错误执行并发服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com