C++11之call_once

多个线程同时调用某个函数,std::call_once可以保证多线程对该函数只调用一次

#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>

std::once_flag flag;

void func() {
    std::call_once(flag, [](){
        std::cout << "hello world" << std::endl;
        sleep(1);
    });
}

int main() {
    std::thread t1(func);
    std::thread t2(func);
    std::thread t3(func);

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

pthread_once实现

#include <iostream>
#include <pthread.h>
#include <unistd.h>

pthread_once_t once = PTHREAD_ONCE_INIT;

void print() {
    std::cout << "hello world" << std::endl;
    sleep(1);
}

void* func(void*) {
    pthread_once(&once, print);
}

int main() {
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, func, NULL);
    pthread_create(&tid2, NULL, func, NULL);
    pthread_create(&tid3, NULL, func, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • std::function 将可调用的函数或者函数指针等,封装成类使用 std::bind 注意其参数是拷贝的方式...
    爱吃花栗鼠的猫阅读 4,048评论 0 1
  • 接着上上节 thread ,本节主要介绍mutex的内容,练习代码地址。<mutex>:该头文件主要声明了与互斥量...
    jorion阅读 14,288评论 2 4
  • 本文根据众多互联网博客内容整理后形成,引用内容的版权归原始作者所有,仅限于学习研究使用,不得用于任何商业用途。 互...
    深红的眼眸阅读 4,819评论 0 0
  • 最近是恰好写了一些c++11多线程有关的东西,就写一下笔记留着以后自己忘记回来看吧,也不是专门写给读者看的,我就想...
    编程小世界阅读 7,400评论 1 2
  • C++11在提供了常规mutex的基础上,还提供了一些易用性的类,本节我们将一起看一下这些类。 1. lock_g...
    许了阅读 12,280评论 2 4