[轉](阿里筆試)使用多線程和sleep函數生成字符串的僞隨機排列

http://blog.csdn.net/jiaowopan/article/details/12009079spa

 

 C/C++(Linux平臺).net

 

注意編譯鏈接時須要連接pthread庫,即g++ XX.cpp -o XX -lpthreadblog

 

[cpp]  view plain copy print ?
 
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. #include <pthread.h>  
  4.   
  5. voidthread(void* v)  
  6. {  
  7.     char ch = *(char*)v;  
  8.     sleep(1);  
  9.     putchar(ch);  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.     pthread_t id[7];  
  15.     int i ,ret;  
  16.     char str[] = "abcdefg";  
  17.     for(i = 0; i < 7; ++i)  
  18.     {  
  19.         ret = pthread_create(&id[i],NULL,thread,&str[i]);  
  20.         if(0 != ret)  
  21.         {  
  22.             printf("create pthread error\n");  
  23.             i--;  
  24.         }  
  25.     }  
  26.     for(i = 0; i < 7; ++i)  
  27.         pthread_join(id[i],NULL);  
  28.     printf("\n");  
  29.     return 0;  
  30.           
  31.       
  32. }  
相關文章
相關標籤/搜索