歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux多線程面試題

Linux多線程面試題

日期:2017/3/1 10:22:30   编辑:Linux編程

前面的選擇題那些跳過,直接看最後的編程題。

第三題(某培訓機構的練習題):

子線程循環 10 次,接著主線程循環 100 次,接著又回到子線程循環 10 次,接著再回到主線程又循環 100 次,如此循環50次,試寫出代碼。

第四題(迅雷筆試題):

編寫一個程序,開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示;如:ABCABC….依次遞推。

第五題(Google面試題)

有四個線程1、2、3、4。線程1的功能就是輸出1,線程2的功能就是輸出2,以此類推.........現在有四個文件ABCD。初始都為空。現要讓四個文件呈如下格式:

A:1 2 3 4 1 2....

B:2 3 4 1 2 3....

C:3 4 1 2 3 4....

D:4 1 2 3 4 1....

請設計程序。


第六題

生產者消費者問題

這是一個非常經典的多線程題目,題目大意如下:有一個生產者在生產產品,這些產品將提供給若干個消費者去消費,為了使生產者和消費者能並發執行,在兩者之間設置一個有多個緩沖區的緩沖池,生產者將它生產的產品放入一個緩沖區中,消費者可以從緩沖區中取走產品進行消費,所有生產者和消費者都是異步方式運行的,但它們必須保持同步,即不允許消費者到一個空的緩沖區中取產品,也不允許生產者向一個已經裝滿產品且尚未被取走的緩沖區中投放產品。

第七題

讀者寫者問題

這也是一個非常經典的多線程題目,題目大意如下:有一個寫者很多讀者,多個讀者可以同時讀文件,但寫者在寫文件時不允許有讀者在讀文件,同樣有讀者讀時寫者也不能寫。

第三題、第四題、第五題第一反應用條件變量來實現。第六題和第七題用讀寫鎖來實現。

第三題、第四題、第五題和我這篇linux多線程學習 (見 http://www.linuxidc.com/Linux/2012-05/60858.htm ) 舉得那例子很相似,只需要少量修改就能完成要求。不多說,直接上代碼。

第四題代碼:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. //#define DEBUG 1
  7. #define NUM 3
  8. int n=0;
  9. pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
  10. pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
  11. void * thread_func(void *arg)
  12. {
  13. int param=(int)arg;
  14. char c='A'+param;
  15. int ret,i=0;
  16. for (; i < 10; i++)
  17. {
  18. pthread_mutex_lock(&mylock);
  19. while (param != n)
  20. {
  21. #ifdef DEBUG
  22. printf("thread %d waiting\n", param);
  23. #endif
  24. ret = pthread_cond_wait(&qready, &mylock);
  25. if (ret == 0)
  26. {
  27. #ifdef DEBUG
  28. printf("thread %d wait success\n", param);
  29. #endif
  30. } else
  31. {
  32. #ifdef DEBUG
  33. printf("thread %d wait failed:%s\n", param, strerror(ret));
  34. #endif
  35. }
  36. }
  37. // printf("%d ",param+1);
  38. printf("%c ",c);
  39. n=(n+1)%NUM;
  40. pthread_mutex_unlock(&mylock);
  41. pthread_cond_broadcast(&qready);
  42. }
  43. return (void *)0;
  44. }
  45. int main(int argc, char** argv) {
  46. int i=0,err;
  47. pthread_t tid[NUM];
  48. void *tret;
  49. for(;i<NUM;i++)
  50. {
  51. err=pthread_create(&tid[i],NULL,thread_func,(void *)i);
  52. if(err!=0)
  53. {
  54. printf("thread_create error:%s\n",strerror(err));
  55. exit(-1);
  56. }
  57. }
  58. for (i = 0; i < NUM; i++)
  59. {
  60. err = pthread_join(tid[i], &tret);
  61. if (err != 0)
  62. {
  63. printf("can not join with thread %d:%s\n", i,strerror(err));
  64. exit(-1);
  65. }
  66. }
  67. printf("\n");
  68. return 0;
  69. }
運行結果:


第五題:

選項A,代碼只需要將NUM改為4,printf("%c ",c)改為printf("%d ",param+1);即可

執行結果如下:


選項B,將全局變量n改為1


選項C,將全局變量n改為2


選項D,將全局變量n改為3

Copyright © Linux教程網 All Rights Reserved