11悄悄 2020-06-11 20:17 采纳率: 0%
浏览 176
已结题

An interview question of Alibaba. Who can find the error of this code when examining the usage of condition variables。pthread_cond_wait()

In the following code, a few lines have been deleted, and the interviewer asks what has been deleted,Who can help,tks!

int n_threads=7;
int print_a=0;
int print_b=0;
int print_c=0;
int print_d=0;
int print_e=0;
int print_f=0;
int print_g=0;
int assigned_job[7]={PRINTA, PRINTB, PRINTC, PRINTD, PRINTE, PRINTF, PRINTG};
void worker(void *t)
{
wait_for_new_work:
pthread_mutex_lock(&threads_wait_for_new_cmd_mutex[my_id]);
pthread_cond_wait(&threads_wake_up_cv[my_id], &threads_wait_for_new_cmd_mutex[my_id]);
pthread_mutex_unlock(&threads_wait_for_new_cmd_mutex[my_id]);
if (thread_control->pls_exit){
pthread_exit(&(thread_control->retval));
}
if (assigned_job[my_id]==PRINTA} print_a++;
else (assigned_job[my_id]==PRINTB} print_b++;
else (assigned_job[my_id]==PRINTC} print_c+;
else (assigned_job[my_id]==PRINTD} print_d++;
else (assigned_job[my_id]==PRINTE} print_e++;
else (assigned_job[my_id]==PRINTF} print_f++;
else (assigned_job[my_id]==PRINTG} print_g++;
pthread_mutex_lock(&threads_done_count_mutex);
threads_done_count++;
if (threads_done_count==n_threads)
pthread_cond_signal(&all_threads_done_cv);
pthread_mutex_unlock(&threads_done_count_mutex);
goto wait_for_new_work;
}
int workers_go(int clear_res)
{
pthread_mutex_lock(&threads_done_count_mutex);
threads_done_count=0;
pthread_mutex_unlock(&threads_done_count_mutex);
for (i=0; i<n_threads; i++){
pthread_mutex_lock(&threads_wait_for_new_cmd_mutex[i]);
pthread_cond_signal(&threads_wake_up_cv[i]);
pthread_mutex_unlock(&threads_wait_for_new_cmd_mutex[i]);
}
pthread_mutex_lock(&threads_done_count_mutex);
if (threads_done_count<n_threads){
printf("n_threads=%d, threads_done_count=%d, waiting for all threads done...\n",
n_threads,
threads_done_count);
pthread_cond_wait(&all_threads_done_cv, &threads_done_count_mutex);
}
pthread_mutex_unlock(&threads_done_count_mutex);
if (verbose)
printf("master: all threads done work\n");
}
int main(int argc, char **argv)
{
/

Create threads pool
*/
cnt=1000;
while(cnt--){
workers_go(1);
sleep(10);
}
}

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-06-11 22:39
    关注

    pthread_cleanup没有调用

    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号