记录下C++11中Thread的使用


2019-10-14 09:27:23
C++11中的多线程使用 (Thread的使用)

这里记录下 demo出现的一些知识点
使用11的标准来构建多线程的应用程序
笔记:
    join调用该函数会阻塞当前线程。阻塞调用者(caller)所在的线程直至被join的std::thread对象标识的线程执行结束。
    detach将当前线程对象所代表的执行实例与该线程对象分离,使得线程的执行可以单独进行。一旦线程执行完毕,它所分配的资源将会被释放。

示例效果:
    demo01:join完成的线程t1,t2是同步执行的 最后才会输出 Main Thread is end;
    demo02:根据demo01进行拓展 如果使用同一个变量 就涉及到线程同步问题,看如果不对共有变量进行加锁 会产生什么现象(程序崩溃)
        锁的使用方法:
        1. mutex m; lock_guard<mutex> lock(m);
        2. mutex m; m.lock();        m.unlock();
    根据demo02进行延伸 加上了锁 输出的数据次序就很整齐了(初步实现了 线程同步),由此延伸出下一个问题:新增加一个线程 对同一个事件的处理速度是否是倍增
    demo03来验证上述猜想
        对于原子操作来说 多线程比单线程还要慢

    demo04:演示detach的使用方法

需要增加的知识点
 

#include <iostream>
#include <thread>        //提供 包括使用thread的多个api函数 
#include <windows.h>
#include <mutex>        //提供mutex 主要用于线程同步
#include <time.h>
using namespace std;

//全局变量 VALUE
int VALUE = 500;
mutex m;

void test01()
{
    for (int i = 0; i < 100; ++i)
    {
        cout << "test01:" << i << endl;
        Sleep(5);
    }
}

void test02()
{
    for (int i = 0; i < 100; ++i)
    {
        cout << "test02:" << i << endl;
        Sleep(5);
    }
}

//不加锁的公有变量 优化后 加锁
void test03()
{
    m.lock();    //这个锁放在这里 和 放在循环体里面是有区别的(具体区别 根据测试结果可知)
    while (VALUE > 0)
    {
        //m.lock();
        VALUE--;
        cout << "Value:" << VALUE << endl;
        //m.unlock();
        Sleep(10);
    }
    m.unlock();
}

//测试两个线程 t1 和 t2 使用join 的现象
void demo01()
{
    thread t1(test01);
    thread t2(test02);

    //step 1
    t1.join();
    t2.join();

    //step 2
    cout << "The Main Thread is end" << endl;
}

void demo02()
{
    thread t3(test03);
    thread t4(test03);
    //thread t5(test03);

    t3.join();
    t4.join();
    //t5.join();
    
}

//验证3个线程的处理速度 比 1个线程处理速度
void demo03()
{
    DWORD begin = GetTickCount64();
    thread t3(test03);
    //thread t4(test03);
    //thread t5(test03);
    //thread t6(test03);
    t3.join();
    //t4.join();
    //t5.join();
    //t6.join();
    DWORD end = GetTickCount64();
    cout << "时间长:" << end - begin << endl;
}

//使用detach 当前线程继续执行 异步操作
void demo04()
{
    thread t1(test03);
    t1.detach();
    cout << "The Main Thread is End" << endl;
}

int main()
{
    demo04();

    system("pause");
    return 0;
}

注意:不要重复的join 不然会触发 当前对象可被 joinable,则 terminate() 报错。
 

猜你喜欢

转载自blog.csdn.net/Wuzm_/article/details/102588918