[转](阿里笔试)使用多线程和sleep函数生成字符串的伪随机排列

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

 

 C/C++(Linux平台)

 

注意编译连接时需要链接pthread库,即g++ XX.cpp -o XX -lpthread

 

  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. }  

posted on 2013-10-13 10:51  brainworm  阅读(362)  评论(1编辑  收藏  举报

导航