gpt4 book ai didi

c - 试图将函数指针传递给 pthread

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

我正在尝试创建一个带有函数指针参数的 pthread,这里首先是将在创建 pthread 时调用的函数..

void *passenger(void *arguements){
struct arg_struct *args = arguements;
int passenger = args->p;
int from_floor = args->f;
int to_floor = args->t;
void (*enter)(int,int) = args->en;
void (*exit)(int,int) = args->ex;
// wait for the elevator to arrive at our origin floor, then get in
int waiting = 1;
while(waiting){
if(current_floor == from_floor && state == ELEVATOR_OPEN && occupancy==0) {
pthread_mutex_lock(&lock);
enter(passenger, 0);
occupancy++;
waiting=0;
pthread_mutex_unlock(&lock);
}
}

// wait for the elevator at our destination floor, then get out
int riding=1;
while(riding) {
if(current_floor == to_floor && state == ELEVATOR_OPEN){
pthread_mutex_lock(&lock);
exit(passenger, 0);
occupancy--;
riding=0;
pthread_barrier_wait(&barr);
pthread_mutex_unlock(&lock);
}
}
}

这里是调用函​​数

void passenger_request(int passenger, int from_floor, int to_floor,void (*enter)(int,int), void(*exit)(int,int))
{
pthread_mutex_lock(&passlock);
struct arg_struct args;
args.p = passenger;
args.f = from_floor;
args.t = to_floor;
args.en = *enter;
args.ex = *exit;
pthread_create(&thread, NULL, &passenger, &args);
//pthread_join(thread, NULL);
pthread_mutex_unlock(&passlock);
// wait for the elevator to arrive at our origin floor, then get in
}

程序在初始化时创建多个乘客时出现段错误,如果我注释掉 pthread_create 行,则不会发生崩溃。我假设这是我为函数指针传递参数的问题,但我不清楚到底发生了什么,因为所有这些指针开始让我感到困惑。任何帮助将不胜感激

还有结构声明..

struct arg_struct{
int p;
int f;
int t;
void *(*ex)(int,int);
void *(*en)(int,int);
};

最佳答案

args.en = *enter;
args.ex = *exit;

enterexit 是函数指针。不要取消引用它们,而是通过 args 直接传递它们。也就是说,您需要:

args.en = enter;
args.ex = exit;

(假设您已正确定义未显示的 struct arg_struct

关于c - 试图将函数指针传递给 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29759807/

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