使用pthread_create创建有限数量的并发运行的线程 成功编译并运行
但是,添加函数指针数组后运行函数,分段错误
哪里错了?
工作服务器编号:0 分段错误
void* workserver(void *arg)
{
int status;
while(true)
{
printf("workserver number: %d\n", (int)arg);
(* job_queue[(int)arg])();
sleep(3);
status = pthread_mutex_lock(&data.mutex);
if(status != 0)
printf("%d lock mutex", status);
data.value = 1;
status = pthread_cond_signal(&data.cond);
if(status != 0)
printf("%d signal condition", status);
status = pthread_mutex_unlock(&data.mutex);
if(status != 0)
printf("%d unlock mutex", status);
}
}
void jobadd(void (*job)())
{
for(int i; i<3; i++)
{
if(idle[i] == 0)
{
job_queue[i] = job;
job;
idle[i] = 1;
}
}
}
void func1()
{
printf("func1 run");
}
void func2()
{
printf("func2 run");
}
void func3()
{
printf("func3 run");
}
void func4()
{
printf("func4 run");
}
int main(int argc, char* argv[])
{
jobadd(func1);
jobadd(func2);
jobadd(func3);
jobrun();
return 0;
}
使用jobadd函数初始化函数指针数组
答案 0 :(得分:-1)
在问题中添加更多细节
job_queue[i] = job
只需将函数指定给函数指针数组
因为无法将函数指针数组直接分配给pthread_create
答案 1 :(得分:-1)
将函数指针数组(* job_queue[(int)arg])();
放在最后
它可以使用以下结果成功调用函数,即使我在func1
中添加无限循环和睡眠,它也不会在func1
现在我正在研究如何使用pthread_cleanup_push
和pop
workserver number:1 func2 run
而(真) { printf(“workserver number:%d \ n”,(int)arg);
status = pthread_mutex_lock(&data.mutex);
//pthread_cleanup_push(
if(status != 0)
printf("%d lock mutex", status);
data.value = 1;
status = pthread_cond_signal(&data.cond);
if(status != 0)
printf("%d signal condition", status);
status = pthread_mutex_unlock(&data.mutex);
if(status != 0)
printf("%d unlock mutex", status);
(* job_queue[(int)arg])();
sleep(1);
void (* clean)(void *);
clean = NULL;
/*
for(int i=0; i<4; i++)
{
if(idle[i] == 0)
{
if(fp[(int)arg] != NULL)
{
idle[running_number[(int)arg]] = 0; // replace its running job
clean = fp[(int)arg];
fp[(int)arg] = job_queue[i];
pthread_cleanup_push(clean, NULL);
(*fp[(int)arg])();
pthread_cleanup_pop(1);
idle[i] = 1;
}
else
{
fp[(int)arg] = job_queue[i];
idle[i] = 1;
running_number[(int)arg] = i;
(*fp[(int)arg])();
}
}
}*/
}