线程基础1

http://www.cnblogs.com/zhuyp1015/archive/2012/04/08/2438288.html

C++11提供了新头文件<thread>、<mutex>、<atomic>、<future>等用于支持多线程。

 基本形式

#include <thread>
#include <iostream>
void hello()
{
    std::cout << "Hello from thread " << std::endl;
}

int main()
{
    std::thread t1(hello);
    t1.join();//join()方法阻塞主线程
    std::cout << "Main Thread" << std::endl;
    return 0;

}

支持stl和lambda

#include <thread>
#include <iostream>
#include <vector>

int main()
{
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i){
        threads.push_back(std::thread([](){
            std::cout << "Hello from lamda thread " << std::this_thread::get_id() << std::endl;
        }));
    }

    for (auto& thread : threads){
        thread.join();
    }
    std::cout << "Main Thread" << "t" << std::this_thread::get_id() << std::endl;
    return 0;
}

线程基础1

可以通过sleep_for来使线程睡眠一定的时间:

#include <thread>
#include <iostream>
#include <mutex>
using namespace std;

int main()
{
    std::mutex m;
    thread t1([&m]()
    {
        std::this_thread::sleep_for(chrono::seconds(10));
        for (int i = 0; i<2; i++)
        {
            m.lock();
            cout << "In t1 ThreadID : " << std::this_thread::get_id() << ":" << i << endl;
            m.unlock();
        }
    });
    thread t2([&m]()
    {
        std::this_thread::sleep_for(chrono::seconds(1));
        for (int i = 0; i<2; i++)
        {
            m.lock();
            cout << "In t2 ThreadID : " << std::this_thread::get_id() << ":" << i << endl;
            m.unlock();
        }
    });
    t1.join();
    t2.join();
    cout << "Main Thread" << endl;
    return 0;
}

线程基础1

延时有这几种类型:nanoseconds、microseconds、milliseconds、seconds、minutes、hours。

#include <thread>
#include <iostream>
#include <vector>
#include <mutex>

struct Counter {
    std::mutex mutex;
    int value;
    Counter() : value(0) {}
    void increment(){
         mutex.lock();        
        ++value;
         mutex.unlock();    
    }
    void decrement(){
        mutex.lock();
        --value;
        mutex.unlock();
    }
};

int main(){
    Counter counter;
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i){
        threads.push_back(std::thread([&](){
            for (int i = 0; i < 10000; ++i){
                counter.increment();
            }
        }));
    }
    for (auto& thread : threads){
        thread.join();
    }
    std::cout << counter.value << std::endl;
    return 0;

}

线程基础1

 

原文链接: https://www.cnblogs.com/yuguangyuan/p/5857243.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    线程基础1

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/398184

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:56
下一篇 2023年4月11日 上午9:56

相关推荐