#include <uhd/convert.hpp>
#include <uhd/exception.hpp>
#include <uhd/types/tune_request.hpp>
#include <uhd/usrp/multi_usrp.hpp>
#include <uhd/utils/safe_main.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/process.hpp>
#include <boost/program_options.hpp>
#include <chrono>
#include <complex>
#include <csignal>
#include <fstream>
#include <iostream>
#include <numeric>
#include <regex>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <atomic>
#include <ctime>
#include <iomanip>

using namespace std::chrono_literals;
namespace po = boost::program_options;

const std::time_t GPS_UNIX_DIFF = 315964800;
const int GPS_UTC_OFFSET = 18;

std::mutex recv_mutex;

static bool stop_signal_called = false;
static bool overflow_message = true;

void sig_int_handler(int) {
    stop_signal_called = true;
}

template <typename samp_type>
void recv_to_file(uhd::usrp::multi_usrp::sptr usrp,
    const std::string& cpu_format,
    const std::string& wire_format,
    const std::vector<size_t>& channel_nums,
    const size_t total_num_channels,
    const std::string& file,
    size_t samps_per_buff,
    unsigned long long num_requested_samples,
    double& bw,
    double time_requested = 0.0,
    bool stats = false,
    bool null = false,
    bool enable_size_map = false,
    bool continue_on_bad_packet = false,
    double file_time_requested = 0.0,
    const std::string& ref = "",
    bool enable_multiple_files = false,
    const std::string& thread_prefix = "")
) {
    // Total number of samples to receive (0 means continuous)
    unsigned long long num_requested_samples = 0;
    unsigned long long num_total_samps = 0;

    // Create a receive streamer
    uhd::stream_args_t stream_args(cpu_format, wire_format);
    stream_args.channels = channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    // Create a buffer pool
    const size_t num_buffers = 20; // Adjust as needed
    struct Buffer {
        std::vector<samp_type> data;
        uhd::rx_metadata_t metadata;
    };
    std::vector<Buffer> buffer_pool(num_buffers, Buffer{std::vector<samp_type>(samps_per_buff), uhd::rx_metadata_t()});

    // Synchronization primitives
    std::mutex mtx;
    std::condition_variable cv;
    std::queue<size_t> free_buffers; // Indices of free buffers
    std::queue<size_t> full_buffers; // Indices of buffers ready to write
    for (size_t i = 0; i < num_buffers; ++i) {
        free_buffers.push(i);
    }

    std::atomic<size_t> active_write_threads(0);

    // File management variables
    std::ofstream outfile;
    std::string current_filename;
    size_t buffers_in_current_file = 0;
    size_t buffers_per_file = (file_time_requested > 0) ?
        static_cast<size_t>(usrp->get_rx_rate(total_num_channels / 1e6) * file_time_requested / samps_per_buff) : 0;

    // Function to get timestamp for filename
    auto get_timestamp = [&](const uhd::rx_metadata_t& md) {
        std::time_t timestamp;
        if (ref == "gpsdo" && md.has_time_spec && md.time_spec.get_full_secs() > 0) {
            // Use USRP time synced with GPSDO
            timestamp = static_cast<std::time_t>(md.time_spec.get_full_secs()) + GPS_UNIX_DIFF - GPS_UTC_OFFSET;
        } else {
            // Use system time
            timestamp = std::time(nullptr);
        }
        // Adjust for Singapore Time (UTC+8)
        timestamp += 8 * 3600;
        std::ostringstream oss;
        std::tm tm = *std::gmtime(&timestamp);
        oss << std::put_time(&tm, "%d%m%Y_%Hhr%Mmin%Ss");
        return oss.str();
    };
    
    std::cout << "Started Streaming...." << std::endl;

    // Receive thread
    std::thread recv_thread([&]() {
        uhd::rx_metadata_t md;
        size_t buffer_index;
        size_t num_rx_samps;

        // Issue stream command
        uhd::stream_cmd_t stream_cmd((num_requested_samples == 0) ?
            uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS :
            uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
        stream_cmd.num_samps = size_t(num_requested_samples);
        stream_cmd.stream_now = false;
        stream_cmd.time_spec = usrp->get_time_now() + uhd::time_spec_t(0.1);
        rx_stream->issue_stream_cmd(stream_cmd);
        
        typedef std::map<size_t, size_t> SizeMap;
        SizeMap mapSizes;
        const auto start_time = std::chrono::steady_clock::now();
        const auto stop_time = start_time + (1s * time_requested);
        // Track time and samps between updating the BW summary
        auto last_update = start_time;
        unsigned long long last_update_samps = 0;

        while (not stop_signal_called
        and (num_requested_samples != num_total_samps or num_requested_samples == 0)
        and (time_requested == 0.0 or std::chrono::steady_clock::now() <= stop_time)) {
        const auto now = std::chrono::steady_clock::now();
            // Get a free buffer
            {
                std::unique_lock<std::mutex> lock(mtx);
                cv.wait(lock, [&]() { return !free_buffers.empty() || stop_signal_called; });
                if (stop_signal_called break;
                buffer_index = free_buffers.front();
                free_buffers.pop();
            }

            // Receive samples into buffer
            size_t num_rx_samps = rx_stream->recv(&buffer_pool[buffer_index].data.front(), samps_per_buff, md, 3.0);
            buffer_pool[buffer_index].metadata = md;

            if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << std::endl
                << thread_prefix << "Timeout while streaming" << std::endl;
            if (++retry_count > MAX_RETRIES) {
                std::cerr << "Maximum retries reached. Exiting... " << std::endl;
                break;
            }
            continue;
            }
            if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
                const std::lock_guard<std::mutex> lock(recv_mutex);
                if (overflow_message) {
                    overflow_message = false;
                    std::cerr
                        << boost::format(
                            "Got an overflow indication. Please consider the following:\n"
                            "  Your write medium must sustain a rate of %0.3fMB/s.\n"
                            "  Dropped samples will not be written to the file.\n"
                            "  Please modify this example for your purposes.\n"
                            "  This message will not appear again.\n")
                        % (usrp->get_rx_rate(channel_nums[0]) * total_num_channels
                            * sizeof(samp_type) / 1e6);
                }
                continue;
            }
            if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
                const std::lock_guard<std::mutex> lock(recv_mutex);
                std::string error = thread_prefix + "Receiver error: " + md.strerror();
                if (continue_on_bad_packet) {
                    std::cerr << error << std::endl;
                    continue;
                }
                else
                    throw std::runtime_error(error);
            }
            
            if (enable_size_map) {
                const std::lock_guard<std::mutex> lock(recv_mutex);
                SizeMap::iterator it = mapSizes.find(num_rx_samps);
                if (it == mapSizes.end())
                    mapSizes[num_rx_samps] = 0;
                mapSizes[num_rx_samps] += 1;
            }

            num_total_samps += num_rx_samps;
            
            last_update_samps += num_rx_samps;
            const auto time_since_last_update = now - last_update;
            if (time_since_last_update > 1s) {
                const std::lock_guard<std::mutex> lock(recv_mutex);
                const double time_since_last_update_s =
                    std::chrono::duration<double>(time_since_last_update).count();
                bw = double(last_update_samps) / time_since_last_update_s;
                last_update_samps = 0;
                last_update = now;
            }

            // Add buffer to full buffers queue
            {
                std::unique_lock<std::mutex> lock(mtx);
                full_buffers.push(buffer_index);
            }
            cv.notify_one();

        }
        
        const auto actual_stop_time = std::chrono::steady_clock::now();

        stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
        rx_stream->issue_stream_cmd(stream_cmd);
        // Signal to write thread to stop
        stop_signal.store(true);
        cv.notify_all();
        
        if (stats) {
            const std::lock_guard<std::mutex> lock(recv_mutex);
            std::cout << std::endl;
            const double actual_duration_seconds =
                std::chrono::duration<float>(actual_stop_time - start_time).count();
            std::cout << boost::format("%sReceived %d samples in %f seconds") % thread_prefix
                % num_total_samps % actual_duration_seconds
                << std::endl;
    
            if (enable_size_map) {
                std::cout << std::endl;
                std::cout << "Packet size map (bytes: count)" << std::endl;
                for (SizeMap::iterator it = mapSizes.begin(); it != mapSizes.end(); it++)
                    std::cout << it->first << ":\t" << it->second << std::endl;
            }
        }
        
    });

    // Write thread
    std::thread write_thread([&]() {
        size_t buffer_index;
        
        while (!stop_signal_called || !full_buffers.empty()) {
            // Get a full buffer
            {
                std::unique_lock<std::mutex> lock(mtx);
                cv.wait(lock, [&]() { return !full_buffers.empty() || stop_signal_called; });
                if (full_buffers.empty()) continue;
                buffer_index = full_buffers.front();
                full_buffers.pop();
                active_write_threads++;
            }

            // Open new file if needed
            if (enable_multiple_files && (!outfile.is_open() || (file_time_requested > 0 && buffers_in_current_file >= buffers_per_file))) {
                // Close previous file
                if (outfile.is_open()) {
                    outfile.close();
                }
                // Get timestamp from metadata
                uhd::rx_metadata_t md = buffer_pool[buffer_index].metadata;
                std::string timestamp = get_timestamp(md);
                current_filename = timestamp + ".dat";
                outfile.open(current_filename.c_str(), std::ofstream::binary);
                buffers_in_current_file = 0;
            } else if (!outfile.is_open()) {
                // Open file if not open
                current_filename = file + ".dat";
                outfile.open(current_filename.c_str(), std::ofstream::binary);
            }

            // Write buffer to file
            outfile.write(reinterpret_cast<const char*>(&buffer_pool[buffer_index].data.front()), samps_per_buff * sizeof(samp_type));
            buffers_in_current_file++;


            // Return buffer to free buffers queue
            {
                std::unique_lock<std::mutex> lock(mtx);
                free_buffers.push(buffer_index);
                active_write_threads--;
            }
            cv.notify_one();
        }

        // Close file
        if (outfile.is_open()) {
            outfile.close();
        }
    });

    // Wait for receive thread to finish
    recv_thread.join();

    // After receiving is finished, report active write threads
    size_t remaining_buffers;
    {
        std::unique_lock<std::mutex> lock(mtx);
        remaining_buffers = full_buffers.size();
    }
    if(remaining_buffers > 0){
      std::cout << "Received is finished, active write threads before sleep: " << remaining_buffers << std::endl;

      // Wait for write thread to finish processing remaining buffers
      while (remaining_buffers > 0) {
          std::this_thread::sleep_for(std::chrono::seconds(2));
          {
              std::unique_lock<std::mutex> lock(mtx);
              remaining_buffers = full_buffers.size();
          }
          if (remaining_buffers > 0) {
              std::cout << "Sleeping 2 seconds as there are active threads..." << std::endl;
              std::cout << "Active write threads: " << remaining_buffers << std::endl;
          }
      }
    }
    

    // Signal to write thread to stop if not already
    stop_signal.store(true);
    cv.notify_all();

    // Wait for write thread to finish
    write_thread.join();

    // Confirm that all write threads are finished
    std::cout << "Received is finished, active write threads before sleep: 0" << std::endl;
}

int UHD_SAFE_MAIN(int argc, char* argv[])
{
    // variables to be set by po
    std::string args, file, type, ant, subdev, ref, wirefmt, channels;
    size_t total_num_samps, spb;
    double rate, freq, gain, bw, total_time, setup_time, lo_offset, file_time; 

    std::vector<std::thread> threads;

    std::vector<size_t> channel_list;
    std::vector<std::string> channel_strings;
    // setup the program options
    po::options_description desc("Allowed options");
    // clang-format off
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
        ("file", po::value<std::string>(&file)->default_value("usrp_samples.dat"), "name of the file to write binary samples to")
        ("type", po::value<std::string>(&type)->default_value("short"), "sample type: double, float, or short")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(0), "total number of samples to receive")
        ("total_duration", po::value<double>(&total_time)->default_value(0), "total number of seconds to receive per loop")
        ("file_duration", po::value<double>(&file_time)->default_value(1), "total number of seconds to receive per file") 
        ("spb", po::value<size_t>(&spb)->default_value(10000), "samples per buffer")
        ("rate", po::value<double>(&rate)->default_value(1e6), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0.0), "RF center frequency in Hz")
        ("lo-offset", po::value<double>(&lo_offset)->default_value(0.0),
            "Offset for frontend LO in Hz (optional)")
        ("gain", po::value<double>(&gain), "gain for the RF chain")
        ("ant", po::value<std::string>(&ant), "antenna selection")
        ("subdev", po::value<std::string>(&subdev), "subdevice specification")
        ("channels,channel", po::value<std::string>(&channels)->default_value("0"), "which channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("bw", po::value<double>(&bw), "analog frontend filter bandwidth in Hz")
        ("ref", po::value<std::string>(&ref), "reference source (internal, external, mimo)")
        ("wirefmt", po::value<std::string>(&wirefmt)->default_value("sc16"), "wire format (sc8, sc16 or s16)")
        ("setup", po::value<double>(&setup_time)->default_value(1.0), "seconds of setup time")
        ("progress", "periodically display short-term bandwidth")
        ("stats", "show average bandwidth on exit")
        ("sizemap", "track packet size and display breakdown on exit. Use with multi_streamer option if CPU limits stream rate.")
        ("null", "run without writing to file")
        ("continue", "don't abort on a bad packet")
        ("skip-lo", "skip checking LO lock status")
        ("int-n", "tune USRP with integer-N tuning")
        ("multi_streamer", "Create a separate streamer per channel.")
        ;
    // clang-format on
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

   // print the help message
    if (vm.count("help")) {
        std::cout << "UHD RX samples to file " << desc << std::endl;
        std::cout << std::endl
            << "This application streams data from a single channel of a USRP "
            "device to a file.\n"
            << std::endl;
        return ~0;
    }

    bool bw_summary = vm.count("progress") > 0;
    bool stats = vm.count("stats") > 0;
    bool null = vm.count("null") > 0;
    bool enable_size_map = vm.count("sizemap") > 0;
    bool continue_on_bad_packet = vm.count("continue") > 0;
    bool multithread = vm.count("multi_streamer") > 0;
    bool enable_multiple_files = (file_duration > 0);
    
    if (enable_size_map)
        std::cout << "Packet size tracking enabled - will only recv one packet at a time!"
        << std::endl;

    // Create a usrp device
    std::cout << "Creating the usrp device with: " << args << "..." << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    
    // Parse channel selection string
    boost::split(channel_strings, channels, boost::is_any_of("\"',"));
    for (size_t ch = 0; ch < channel_strings.size(); ch++) {
        try {
            int chan = std::stoi(channel_strings[ch]);
            if (chan >= static_cast<int>(usrp->get_rx_num_channels()) || chan < 0) {
                throw std::runtime_error("Invalid channel(s) specified.");
            }
            else {
                channel_list.push_back(static_cast<size_t>(chan));
            }
        }
        catch (std::invalid_argument const& c) {
            throw std::runtime_error("Invalid channel(s) specified.");
        }
        catch (std::out_of_range const& c) {
            throw std::runtime_error("Invalid channel(s) specified.");
        }
    }

    // Lock mboard clocks
    if (vm.count("ref")) {
        usrp->set_clock_source(ref);
        usrp->set_time_source(ref);
    }

    // Set subdevice spec
    if (vm.count("subdev")) {
        usrp->set_rx_subdev_spec(subdev);
    }
    
    std::cout << "Using Device: " << usrp->get_pp_string() << std::endl;

    // set the sample rate
    if (rate <= 0.0) {
        std::cerr << "Please specify a valid sample rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate / 1e6) << std::endl;
    usrp->set_rx_rate(rate, uhd::usrp::multi_usrp::ALL_CHANS);
    std::cout << boost::format("Actual RX Rate: %f Msps...")
        % (usrp->get_rx_rate(channel_list[0]) / 1e6)
        << std::endl
        << std::endl;

    // set the center frequency
    if (vm.count("freq")) { // with default of 0.0 this will always be true
        std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq / 1e6)
            << std::endl;
        std::cout << boost::format("Setting RX LO Offset: %f MHz...") % (lo_offset / 1e6)
            << std::endl;
        uhd::tune_request_t tune_request(freq, lo_offset);
        if (vm.count("int-n"))
            tune_request.args = uhd::device_addr_t("mode_n=integer");
        for (size_t chan : channel_list)
            usrp->set_rx_freq(tune_request, chan);
        std::cout << boost::format("Actual RX Freq: %f MHz...")
            % (usrp->get_rx_freq(channel_list[0]) / 1e6)
            << std::endl
            << std::endl;
    }

    // set the rf gain
    if (vm.count("gain")) {
        std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
        usrp->set_rx_gain(gain, uhd::usrp::multi_usrp::ALL_CHANS);
        std::cout << boost::format("Actual RX Gain: %f dB...")
            % usrp->get_rx_gain(channel_list[0])
            << std::endl
            << std::endl;
    }

    // set the IF filter bandwidth
    if (vm.count("bw")) {
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % (bw / 1e6)
            << std::endl;
        for (size_t chan : channel_list)
            usrp->set_rx_bandwidth(bw, chan);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...")
            % (usrp->get_rx_bandwidth(channel_list[0]) / 1e6)
            << std::endl
            << std::endl;
    }

    // set the antenna
    if (vm.count("ant"))
        for (size_t chan : channel_list)
            usrp->set_rx_antenna(ant, chan);

    // Allow for some setup time
    std::this_thread::sleep_for(1s * setup_time);

    // Set the device timestamp to 0
    usrp->set_time_now(uhd::time_spec_t(0.0));

    // check Ref and LO Lock detect
    if (not vm.count("skip-lo")) {
        for (size_t channel : channel_list) {
            std::cout << "Locking LO on channel " << channel << std::endl;
            check_locked_sensor(
                usrp->get_rx_sensor_names(channel),
                "lo_locked",
                [usrp, channel](const std::string& sensor_name) {
                    return usrp->get_rx_sensor(sensor_name, channel);
                },
                setup_time);
        }
        if (ref == "mimo") {
            check_locked_sensor(
                usrp->get_mboard_sensor_names(0),
                "mimo_locked",
                [usrp](const std::string& sensor_name) {
                    return usrp->get_mboard_sensor(sensor_name);
                },
                setup_time);
        }
        if (ref == "external") {
            check_locked_sensor(
                usrp->get_mboard_sensor_names(0),
                "ref_locked",
                [usrp](const std::string& sensor_name) {
                    return usrp->get_mboard_sensor(sensor_name);
                },
                setup_time);
        }
        if (ref == "gpsdo") {
            check_locked_sensor(
                usrp->get_mboard_sensor_names(0),
                "ref_locked",
                [usrp](const std::string& sensor_name) {
                    return usrp->get_mboard_sensor(sensor_name);
                },
                setup_time);
                // Synchronize USRP time to GPS time
                uhd::sensor_value_t gps_time = usrp->get_mboard_sensor("gps_time", 0);
                double usrp_time = gps_time.to_real(); // GPS time in seconds since epoch
                usrp->set_time_next_pps(uhd::time_spec_t(usrp_time + 1.0)); // Set time at next PPS
                std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for time to be set
            }
        }
    }
    

    if (total_num_samps == 0) {
        std::signal(SIGINT, &sig_int_handler);
        std::cout << "Press Ctrl + C to stop streaming..." << std::endl;
    }

    const double req_disk_rate = usrp->get_rx_rate(channel_list[0]) * channel_list.size()
        * uhd::convert::get_bytes_per_item(wirefmt);
    const double disk_rate_meas = disk_rate_check(
        uhd::convert::get_bytes_per_item(wirefmt), channel_list.size(), spb, file);
    if (disk_rate_meas > 0 && req_disk_rate >= disk_rate_meas) {
        std::cerr
            << boost::format(
                "  Disk write test indicates that an overflow is likely to occur.\n"
                "  Your write medium must sustain a rate of %0.3fMB/s,\n"
                "  but write test returned write speed of %0.3fMB/s.\n"
                "  The disk write rate is also affected by system load\n"
                "  and OS/disk caching capacity.\n")
            % (req_disk_rate / 1e6) % (disk_rate_meas / 1e6);
    }

    std::vector<size_t> chans_in_thread;
    std::vector<double> rates(channel_list.size());

#define recv_to_file_args(format)                                                    \
    (usrp,                                                                           \
        format,                                                                      \
        wirefmt,                                                                     \
        chans_in_thread,                                                             \
        channel_list.size(),                                                         \
        multithread ? "ch" + std::to_string(chans_in_thread[0]) + "_" + file : file, \
        spb,                                                                         \
        total_num_samps,                                                             \
        rates[i],                                                                    \
        total_time,                                                                  \
        stats,                                                                       \
        null,                                                                        \
        enable_size_map,                                                             \
        continue_on_bad_packet,                                                      \
        file_time,                                                                   \
        ref,                                                                         \
        th_prefix)
    for (size_t i = 0; i < channel_list.size(); i++) {
        std::string th_prefix = "";
        if (multithread) {
            chans_in_thread.clear();
            chans_in_thread.push_back(channel_list[i]);
            th_prefix = "Thread " + std::to_string(i) + ":\n";
        }
        else {
            chans_in_thread = channel_list;
        }
        threads.push_back(std::thread([=, &rates]() {
            // recv to file
            if (wirefmt == "s16") {
                if (type == "double")
                    recv_to_file<double> recv_to_file_args("f64");
                else if (type == "float")
                    recv_to_file<float> recv_to_file_args("f32");
                else if (type == "short")
                    recv_to_file<short> recv_to_file_args("s16");
                else
                    throw std::runtime_error("Unknown type " + type);
            }
            else {
                if (type == "double")
                    recv_to_file<std::complex<double>> recv_to_file_args("fc64");
                else if (type == "float")
                    recv_to_file<std::complex<float>> recv_to_file_args("fc32");
                else if (type == "short")
                    recv_to_file<std::complex<short>> recv_to_file_args("sc16");
                else
                    throw std::runtime_error("Unknown type " + type);
            }
            }));
        if (!multithread) {
            break;
        }
    }


    if (total_time == 0) {
        if (total_num_samps > 0) {
            total_time = std::ceil(total_num_samps / usrp->get_rx_rate());
        }
    }

    // Wait a bit extra for the first updates from each thread
    std::this_thread::sleep_for(500ms);

    const auto end_time = std::chrono::steady_clock::now() + (total_time - 1) * 1s;

    while (threads.size() > 0
        && (std::chrono::steady_clock::now() < end_time || total_time == 0)
        && !stop_signal_called) {
        std::this_thread::sleep_for(1s);

        // Remove any threads that are finished
        for (size_t i = 0; i < threads.size(); i++) {
            if (!threads[i].joinable()) {
                // Thread is not joinable, i.e. it has finished and 'joined' already
                // Remove the thread from the list.
                threads.erase(threads.begin() + i);
                // Clear last bandwidth value after thread is finished
                rates[i] = 0;
            }
        }
        // Report the bandwidth of remaining threads
        if (bw_summary && threads.size() > 0) {
            const std::lock_guard<std::mutex> lock(recv_mutex);
            std::cout << "\t"
                << (std::accumulate(std::begin(rates), std::end(rates), 0) / 1e6
                    / threads.size())
                << " Msps" << std::endl;
        }
    }

    // join any remaining threads
    for (size_t i = 0; i < threads.size(); i++) {
        if (threads[i].joinable()) {
            threads[i].join();
        }
    }

    // finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}

 

C++ Online Compiler

Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++ and start coding!

Read inputs from stdin

OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    string name;
    cout << "Enter name:";
    getline (cin, name);
    cout << "Hello " << name;
    return 0;
}

About C++

C++ is a widely used middle-level programming language.

  • Supports different platforms like Windows, various Linux flavours, MacOS etc
  • C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction.
  • Case-sensitive
  • C++ is a compiler based language
  • C++ supports structured programming language
  • C++ provides alot of inbuilt functions and also supports dynamic memory allocation.
  • Like C, C++ also allows you to play with memory using Pointers.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
   //code
}
else {
   //code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression){    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
......    
    
default:     
 code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
// code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
 // code 
} while (condition); 

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.

How to declare a Function:

return_type function_name(parameters);

How to call a Function:

function_name (parameters)

How to define a Function:

return_type function_name(parameters) {  
 // code
}