参加了阿里的一个面试,面试官从正常代码里删除了几行,要求我找出下面这段代码的错误。我看了半天也没找到问题。其中worker()函数是7个线程的执行函数。各位爸爸,谁知道下面这段代码错在哪,原题如下:
假设多核的CPU,没有任何竞争问题。希望print_a, print_b, ... print_g在结束的时候都是1000。下面的代码是否可以做到?如果做不到,是什么原因,如何修改?
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_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
");
}
int main(int argc, char **argv)
{
/*
Create threads pool
*/
cnt=1000;
while(cnt--){
workers_go(1);
sleep(10);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…