FLY
Life is like riding a bicycle, to keep your balance, you must keep moving.

源代码:

 1 #include <iostream>
 2 #include <thread>
 3 #include <string>
 4 #include <chrono>
 5 
 6 void th1()
 7 {
 8     for(int i=0; i<5; i++){
 9         std::cout<<"th1--"<<i<<std::endl;
10         std::this_thread::sleep_for(std::chrono::seconds(1));//@1
11     }
12 }
13 void th2()
14 {
15     for(int i=0; i<5; i++){
16         std::cout<<"th2--"<<i<<std::endl;
17         std::this_thread::sleep_for(std::chrono::seconds(1));//@2
18     }
19 }
20 int main(){
21     std::cout<<"--begin--"<<std::endl;
22     std::thread t1(th1);
23     std::this_thread::sleep_for(std::chrono::seconds(5));//@3
24     std::thread t2(th2);
25 //    t1.join();//$1
26 //    t2.join();//$2
27 
28     for(int i=0; i<10; i++){
29         std::cout<<"main th --"<<i<<std::endl;
30     }
31     std::this_thread::sleep_for(std::chrono::seconds(5));//@4
32     t1.detach();//$3
33     t2.detach();//$4
34     std::cout<<"--end--"<<std::endl;
35     return 0;
36 }

 1.主线程没有执行等待(即@3,@4注释掉):

--begin--
main th --0
main th --1
main th --2
main th --3
main th --4
main th --5
main th --6
main th --7
main th --8
main th --9
--end--

 由此可见,多线程中子线程的执行是在主线程有空闲的条件下。即,如果主线程忙,或者是没有执行等待,那么,子线程是不会执行的。

2. 在@3处等待,@4处不等待:

--begin--
th1--0
th1--1
th1--2
th1--3
th1--4
main th --0
main th --1
main th --2
main th --3
main th --4
main th --5
main th --6
main th --7
main th --8
main th --9
--end--

主线程在@3 处,t1线程已经创建,则在主线程停顿的 5秒中,等待线程 t1 执行,在线程 t1 执行完毕后,有时还有时间,主线程继续等待完 5 秒后,重新执行。

3. 在@3不等待,@4处等待:

--begin--
main th --0
main th --1
main th --2
main th --3
main th --4
main th --5
main th --6
main th --7
main th --8
main th --9
th1--0
th2--0
th1--1
th2--1
th1--2
th2--2
th1--3
th2--3
th1--4
th2--4
--end--

 主线程在@4处,t1,t2线程已经创建,则在主线程停顿的 5秒中,等待线程 t1,t2 执行,在线程 t1,t2 执行完毕后,有时还有时间,主线程继续等待完 5 秒后,重新执行。

 4.若将@1处的等待时间改为2:

--begin--
main th --0
main th --1
main th --2
main th --3
main th --4
main th --5
main th --6
main th --7
main th --8
main th --9
th1--0
th2--0
th2--1
th1--1
th2--2
th2--3
th1--2
th2--4
--end--

 主线程在@4处,t1,t2线程已经创建,则在主线程停顿的 5秒中,等待线程 t1,t2 执行,在5s时间段内,t1每隔2s循环一次,t2每隔1s循环一次,因此t1没结束,t2循环结束,主线程继续等待完 5 秒后,重新执行。

 

 

 

 

posted on 2012-11-29 15:46  juice_li  阅读(2090)  评论(0编辑  收藏  举报