c++线程并发---线程同步-创新互联

1.什么是同步?

某个线程需要等待另外一个线程的任务完成,才可以执行的自己的任务,被称为同步。

十多年的华蓥网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整华蓥建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“华蓥网站设计”,“华蓥网站推广”以来,每个客户项目都认真落实执行。2.c++ 条件变量
#include#include#include#include#includestatic std::mutex              mtx;
static std::condition_variable cv;
void                           runthread(int index)
{
    while (1)
    {
        std::unique_lock< std::mutex >lck(mtx);  //上锁
        fprintf(stderr, "thread:%d is waiting.\n", index);
        cv.wait(lck);  // wait 解锁,然后加锁
        fprintf(stderr, "thread:%d is sleep.\n", index);
        std::this_thread::sleep_for(std::chrono::seconds(5));
        fprintf(stderr, "thread:%d is wakeup.\n", index);
    }
}

void runthread_1(int index)
{
    std::unique_lock< std::mutex >lck(mtx); //
    fprintf(stderr, "thread:%d is waiting.\n", index);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    fprintf(stderr, "thread:%d is wakeup.\n", index);
}
int main()
{
    fprintf(stderr, "pid:%d\n", getpid());

    std::thread* pt[5];
    for (int i = 0; i< 5; i++)
    {
        pt[i] = new std::thread(runthread, i);  //创建5个线程
    }

    for (int i = 0; i< 3; i++)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        fprintf(stderr, "main thread sleep %d seconds\n", i);
    }
    cv.notify_all();     
    //  cv.notify_one();    // 唤醒其中的一个线程,此时该线程会执行完cv.wait(lck);
    // 由阻塞状态变成运行状态,此时m_mtx会锁上,因此,下面的runthread_1会被锁上,进而不能够打印输出
    // new std::thread(runthread_1, 10);

    for (int i = 0; i< 5; i++)
    {
        if (pt[i]->joinable())
        {
            pt[i]->join();
            delete pt[i];
            pt[i] = NULL;
        }
    }
    return 0;
}
3.std::future

使用一次性future来模拟一类事件,若线程需要等待某一个事件发生,则会以一个恰当的方式取得一个future,它代表目标事件,可以一边等待事件的发生,一边执行其他任务。

就好比: 去高铁站做高铁,你要等待高铁的到来,而在高铁来之前,你可以吃饭,玩手机等,等待其他事情的发生。

#include#include#include#includeusing namespace std;
//g++ -std=c++0x -pthread future.cpp
int printname(string a,int n)
{
       for(int i=0;i

thread1
thread1
thread1
2
3

4.c++ 异步处理--std::async

参数列表:

std::launch::deferred //等待future运行wait或者get时才会继续运行。

std::launch::async    //运行新的线程

std::launch::deferred| std::launch::async  //交由实现自行选择运行方式

auo f3=std::async(std::launch::async,printname,"thread2",3);
    auo f4=std::async(std::launch::deferred,printname,"thread3",3);
    auo f5=std::async(std::launch::deferred|std::launch::async,printname,"thread4",3);

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网站栏目:c++线程并发---线程同步-创新互联
文章网址:http://myzitong.com/article/dsgcci.html