栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【c++】 thread

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【c++】 thread

thread

创建一个简单线程

#include 
#include 
#include 
#include 


void f1(int n)
{
    for (int i=0;i<5;i++)
    {
        std::cout << "Thread 1 executingn";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void f2(int& n)
{
    for (int i=0;i<5;i++)
    {
        std::cout << "Thread 2 executingn";
        ++n;
        //Blocks the execution of the current thread for at least the specified sleep_duration
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main()
{
    int n = 1;
    std::thread t1(f1,10);
    std::thread t2(f2,std::ref(n));

    std::thread::id t1_id = t1.get_id();
    std::thread::id t2_id = t2.get_id();
    std::cout << "t1's id: " << t1_id << 'n';
    std::cout << "t2's id: " << t2_id << 'n';
    t1.join(); // waits for the thread to finish its execution
    t2.join();
    std::cout << "now n = " << n << std::endl;

}
// g++ thread.cpp -o thread -Wall -g -lpthread
mutex

mutex是用来保证线程同步的,防止不同的线程同时操作同一个共享数据

#include 
#include 
#include 
#include 
#include 
#include 


std::map page;
std::mutex m;

void save_page(const std::string& url)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::string value = "res";
    std::lock_guard lg(m); // lock_guard implements a strictly scope-based mutex ownership wrapper
    // m.lock();
    page[url] = value; 
    // m.unlock();
}

void work_add(std::mutex& m,int& a)
{
    std::lock_guard lk(m);
    for (int i=0;i<5;i++)
    {
        a = a+1;
        std::cout << "add count = " << a < lk(m); // 主线程拿锁
    std::cout << "change i = 1" << std::endl;
    i=1;
    lk.unlock();
    std::cout << "notify one" << std::endl;
    cv.notify_one();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    lk.lock();

    lk.unlock();
    std::cout << "notify all" << std::endl;
    cv.notify_all();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    lk.lock();

    t1.join();
    t2.join();
    t3.join();


}
promise
#include 
#include 
#include 
#include 

void set_promise(std::promise p)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    p.set_value(100);
}


int main()
{
    std::promise p_int;
    std::future f_int = p_int.get_future();
    // 一个std::promise实例只能与一个std::future关联共享状态,当在同一个std::promise上反复调用get_future会抛出future_error异常
    // std::future f_int2 = p_int.get_future();
    std::thread t(set_promise,std::move(p_int));
    std::cout << "f_int.get()=" << f_int.get() << std::endl;
    // 一定要加join,等待线程结束
    t.join();   
    return 0;
}
//g++ thread_future2.cpp -o future2 -Wall -g -lpthread
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号