首页 > 其他分享 >cpp multi thread sync via std::atomic<bool>

cpp multi thread sync via std::atomic<bool>

时间:2023-05-01 14:57:08浏览次数:45  
标签:std multi via chrono now time include atomic

#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <ctime>
#include <fstream>
#include <functional>
#include <future>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <mutex>
#include <queue>
#include <random>
#include <sstream>
#include <thread>
#include <uuid/uuid.h>
#include <vector>

std::string get_time_now()
{
    std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
    time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now);
    struct tm tm_info = *localtime(&raw_time);
    std::stringstream ss;
    std::chrono::seconds seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
    std::chrono::milliseconds mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    std::chrono::microseconds micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
    std::chrono::nanoseconds nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S")
       << std::setw(3) << std::setfill('0') << std::to_string(mills.count() - seconds.count() * 1000) << ","
       << std::setw(3) << std::setfill('0') << std::to_string(micros.count() - mills.count() * 1000)
       << std::setw(3) << std::setfill('0') << std::to_string(nanos.count() - micros.count() * 1000);
    return ss.str();
}

char *uuid_value = (char *)malloc(40);
char *get_uuid()
{
    uuid_t new_uuid;
    uuid_generate(new_uuid);
    uuid_unparse(new_uuid, uuid_value);
    return uuid_value;
}

std::atomic<bool> _is_write_finish(false);

void write_into_file(const std::string &file_name, const int &len)
{
    std::fstream w_file(file_name, std::ios::app);
    if (!w_file.is_open())
    {
        std::cout << "Create or open " << file_name << " failed" << std::endl;
        return;
    }

    std::stringstream ss;
    int loops = len / 1000000;
    int remainder = len % 1000000;
    static int num = 0;
    if (loops > 0)
    {
        for (int i = 0; i < loops; i++)
        {
            for (int j = 0; j < 1000000; j++)
            {
                ss << ++num << "," << get_uuid() << std::endl;
            }
            w_file << ss.str();
            std::cout<<num<<std::endl;
            ss=std::stringstream();
        }
    }

    if(remainder>0)
    {
        for(int i=0;i<remainder;i++)
        {
            ss<<++num<<","<<get_uuid()<<std::endl;
        }
        w_file<<ss.str();
        ss=std::stringstream();
    }

    w_file.close();
    _is_write_finish=true;
}

void print_file(const std::string&file_name)
{
    while(!_is_write_finish.load())
    {        
    }
    std::fstream read_file(file_name,std::ios::in);
    if(!read_file.is_open())
    {
        std::cout<<"Open "<<file_name<<" failed!"<<std::endl;
        return;
    }

    std::string line;
    while(getline(read_file,line))
    {
        std::cout<<line<<std::endl;
    }
    read_file.close();
    std::cout<<get_time_now()<<",finishi in "<<__FUNCTION__<<std::endl;
}

void atomic_write_read_sync(const std::string &file_name, const int &len)
{
    std::thread t1(write_into_file,std::cref(file_name), std::cref(len));
    std::thread t2(print_file,std::cref(file_name));
    t1.join();
    t2.join();
    std::cout<<get_time_now()<<",finish in "<<__FUNCTION__<<std::endl;
}

int main(int args, char **argv)
{
    atomic_write_read_sync(argv[1],atoi(argv[2]));
}

 

Compile

g++ -std=c++2a -I. *.cpp -o h1 -luuid -lpthread

 

Run

./h1 log.txt 11111111

 

 

 

 

The key to synchronize multiple threads in before-and-write relationships located at std::atomic<bool> the third variable,with false default value,when before thread finished set the atomic variable to true

While in the after thread,in while loop it run nothing because the load() is false,until the atomic variable is true,it run the following code sequentially.

标签:std,multi,via,chrono,now,time,include,atomic
From: https://www.cnblogs.com/Fred1987/p/17366526.html

相关文章

  • c++11:std::forward,完美转发
    目录1、不完美转发2、完美转发2.1、引用折叠2.2、std::forward1、不完美转发所谓完美转发,是指在函数模板中,完全按照模板的参数的类型,将参数传递给函数模板中调用的另一个函数。比如:template<typenameT>voidIamForwording(Tt){IrunCodeActually(t);}上面的例子中,IamF......
  • 问题解决:Component name "xxx" should always be multi-word vue/multi-word-compone
    如题,原因是单个单词命名时语法检测无法通过,可以在导出组件时通过name属性给组件名加一个后缀,比如Component。<script>exportdefault{//当组件名为一个单词时,语法检查是无法通过的,可以设置name的值为2个单词来规避检查。name:'HomeComponent'}<......
  • C++-std::this_thread::get_id()-获取线程id
    C++-std::this_thread::get_id()-获取线程idstd::this_thread::get_id()头文件:<thread>函数:std::this_thread::get_id()用例:std::thread::idthread_id=std::this_thread::get_id();std::thread对象的成员函数get_id()头文件:<thread>函数:std::thread::idget_id()用例:......
  • 10 Abbreviations You Should Know
    10AbbreviationsYouShouldKnowASAPassoonaspossibleRSVPpleaseresponselaterRIPrestinpeacee.g.takinganexamplei.e.inotherwordshttps://www.bilibili.com/video/BV1uW41187D4/......
  • Linux安装Fastdfs
    前言:还是和以前一样,linux安装软件的目录都是data目录 1.进入data目录,创建libfastcommon目录并进入该目录cd/datamkdirlibfastcommoncdlibfastcommon 2.yum安装一下unzipyuminstallzipunzip-y 3.上传"libfastcommon_v1.40.zip"文件到当前目录(/data/li......
  • Feign使用MultipartFile
    Feign的方法参数使用MultipartFileFeign的方法参数使用MultipartFile,不能直接用,需要做一些配置。依赖包:<dependency><groupId>io.github.openfeign.form</groupId><artifactId>feign-form</artifactId><version>3.8.0</version></depend......
  • User installations are disabled via policy on the machine. 安装python
    Userinstallationsaredisabledviapolicyonthemachine. 解决办法1、在运行里输入gpedit.msc;(grouppolicy)组策略2、计算机配置管理>>管理模板>>windows组件>>windowsInstaller>>禁止用户安装;3、打开它禁用此项就可以了。    ......
  • Representation Learning for Attributed Multiplex Heterogeneous Network
    目录概符号说明各种定义HeterogeneousnetworkAttributednetworkAttributedmultiplexnetwork代码CenY.,ZouX.,ZhangJ.,YangH.,ZhouJ.andTangJ.Representationlearningforattributedmultiplexheterogeneousnetwork.KDD,2019.概本文在Attributed(结......
  • 一统天下 flutter - widget 布局类(可以有多个子): CustomMultiChildLayout - 自定义多
    源码https://github.com/webabcd/flutter_demo作者webabcd一统天下flutter-widget布局类(可以有多个子):CustomMultiChildLayout-自定义多组件布局示例如下:lib\widget\layout\custom_multi_child_layout.dart/**CustomMultiChildLayout-自定义多组件布局*......
  • os.listdir()读出来的文件顺序和本地的顺序不一致,应该怎么做呢?
    今日鸡汤冉冉几盈虚,澄澄变今古。大家好,我是皮皮。一、前言前几天在帮助粉丝解决问题的时候,遇到一个简单的小需求,这里拿出来跟大家一起分享,后面再次遇到的时候,可以从这里得到灵感。二、需求澄清问题如下所示:问题截图如下所示:三、实现过程这里【崔峰】给了一个思路,使用编码的方式进......