示例一:

#include <iostream>
#include <thread>

using namespace std;

void thread1()
{
    for (int n = 0; n<4; n++)
        cout << "i am child thread" << endl;
}//抢占式

int main()
{
    thread t(thread1);
    t.detach();//分离方式。主线程先结束的话,进程会结束,子线程亦会结束(不论子线程是否已执行完)
    //t.join();//阻塞方式。

    for (int n = 0; n<4; n++)
        cout << "i am main thread" << endl;



    return 0;
}

 

示例二:

#include <iostream>
#include <thread>

using namespace std;

void thread1()
{
    for (int n = 0; n<4; n++)
        cout << "i am child thread" << endl;
}//抢占式

int main()
{
    thread t(thread1);
    t.detach();//分离方式。主线程先结束的话,进程会结束,子线程亦会结束(不论子线程是否已执行完)
               //t.join();//阻塞方式。

    for (int n = 0; n<4; n++)
        cout << "i am main thread" << endl;


    while (true)
    {
        std::this_thread::sleep_for(std::chrono::microseconds(3));
    }

    return 0;
}

 主线程加入while循环,一直执行不退出。子线程会执行完毕,不会发生:子线程未执行完,主线程退出了,子线程被迫结束。

 

 

示例三:

#include <iostream>
#include <thread>

using namespace std;

void thread1()
{
    for (int n = 0; n<4; n++)
        cout << "i am child thread" << endl;
}//抢占式

int main()
{
    thread t(thread1);
    t.join();//阻塞方式。

    for (int n = 0; n<4; n++)
        cout << "i am main thread" << endl;



    return 0;
}

子线程执行完了之后,主线程才会执行

 

示例四:

#include <iostream>
#include <thread>

using namespace std;

void workFun(int index)
{

    for (int i = 0; i < 100; i++)
    {
        cout << index << " child thread " << i << endl;
    }
        

}

int main()
{
    thread t[3];
    for (int n = 0; n<3; n++)
    {
        t[n] = thread(workFun, n);
        t[n].join();
    }

    for (int i = 0; i<4; i++)
        cout <<"i am main thread "<< i << endl;

    return 0;
}

子线程会顺序执行,t[0]执行完--->t[1]执行完----->t[2]执行完

主线程执行

--------------------------------------------------

示例五:

#include <iostream>
#include <thread>

using namespace std;

void workFun(int index)
{

    for (int i = 0; i < 100; i++)
    {
        cout << index << " child thread " << i << endl;
    }
        

}

int main()
{
    thread t[3];
    for (int n = 0; n<3; n++)
    {
        t[n] = thread(workFun, n);
    }

    for (int n = 0; n<3; n++)
    {
        t[n].join();
    }

    for (int i = 0; i<4; i++)
        cout <<"i am main thread "<< i << endl;
return 0; }

子线程 t[0]   t[1]   t[2] 会并行执行。

子线程执行完成之后,主线程执行。

 

posted on 2021-02-03 20:47  邶风  阅读(143)  评论(0编辑  收藏  举报