Thursday, February 15, 2018

Compare and Swap(CAS) implementation for counter shared data in C++

 implementation in simple increase counter:

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

std::atomic<int> count(0);
std::mutex n_mutux;

void increase_counter()
{
    int old_value = count.load(); ;
    while (!count.compare_exchange_weak(old_value, old_value +1))
    {
    }



}


int main() {
    unsigned int n = std::thread::hardware_concurrency();
    std::cout << n << " concurrent threads are supported.\n";
    int thread_num =10;
    std::thread t[thread_num];
    for(int i=0;i<thread_num;i++)
    {
        t[i]=std::thread((increase_counter));
    }

    for(int i=0;i<thread_num;i++)
    {
        t[i].join();
    }
   std::cout<<count;
}





implementation with vector and structure:



//// Created by Laxmi Kadariya on 2/14/18.//
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>



std::atomic<int> count(0);
struct Counter {
    int value;

    Counter() : value(0){}

    void increment(){
        int old_value = count.load(); ;
        while (!count.compare_exchange_weak(old_value, old_value +1))
        {
        }
//        ++value;
    }
};

int main(){
    Counter counter;

    std::vector<std::thread> threads;
    for(int i = 0; i < 10; ++i){
        threads.push_back(std::thread([&counter](){
            for(int i = 0; i < 1000; ++i){
                counter.increment();
            }
        }));
    }

    for(auto& thread : threads){
        thread.join();
    }

    std::cout << count << std::endl;
//    std::cout << counter.value << std::endl;

    return 0;
}

Wednesday, February 14, 2018

Reading chunk of data from a file calling a function using C++

#include <iostream>
#include <fstream>
#include <string>
#include<vector>
using namespace std;
bool generate_chunks(ifstream &fp,int chunk_size,string &buffer)
{
    vector<char>data(chunk_size);
    fp.read(&data[0],chunk_size);
    std::streamsize datasize = fp.gcount();
    if(datasize == 0)
    {
        cout<<"here";
        return false;
    }
    buffer =string(data.begin(),data.end());
    return true;

}
int main() {
    std::cout << "Hello, World!" << std::endl;
    ifstream myfile;
    bool test;
    string data;

    myfile.open("../test.dat",ifstream::binary);

   if(myfile.is_open()) {


        if(generate_chunks(myfile, 1024, data))

        {
            cout<<data;
        }

   }


    myfile.close();

    return 0;
}

Tuesday, February 13, 2018

reading of chunk of data from the binary file and unpacking the data using struct construct in python

import struct

class parser():
    def __init__(self):
        self.data = ""        self.offset = 0
    def add_data(self,data):
        self.data = self.data[self.offset:]
        # print (self.data)        
        self.data += data
        self.offset = 0

    def parse_header(self):
        l,n = struct.unpack('>hh',self.data[self.offset: self.offset+4])
        if len(self.data) - self.offset >l:
            status = True        
        else:
            status = False
        return l,n,status



    def parse_QuoteORTrade_data(self):
        val,type = struct.unpack('>hs',self.data[self.offset:self.offset+3])
        # print(val,type)        
        self.update_offset(3)
        if(type == b'Q'):

            # sym,price,size = struct.unpack('>5shh',self.data[self.offset:self.offset+9])            self.update_offset(17)
            # print (sym,price,size)            
            self.update_offset(val-20)
        if(type == b'T'):

            sym,price,size = struct.unpack('>5shq',self.data[self.offset:self.offset+15])
            self.update_offset(15)
            print (sym,price,size)
            self.update_offset(val-18)




    def update_offset(self,offset):
        self.offset = self.offset+ offset

def ReadInChunk(fileobj,ChunkSize= 50):
    while True:
        data = fileobj.read(ChunkSize)
        if not data:
            break
        yield data



def read_file():
    f = open("input.dat","rb")
    return  f



if __name__ == "__main__" :
    offset_chunk = 0    obj=parser()
    fp = read_file()

    for chunk in ReadInChunk(fp):

        obj.add_data(chunk)
        # print (obj.data)       
        while True:
            try:
                length,num,status = obj.parse_header()


            except Exception,e:
                break            
            if(status == False):
                break
            obj.update_offset(4)
            for data in range(num):

                obj.parse_QuoteORTrade_data()





    fp.close()

Tuesday, February 6, 2018

Binary Tree creation with c++ using class and inorder traversal without recursion

//// Created by Laxmi Kadariya on 2/5/18.
//This is the source code to create binary tree with class in c++//#include "iostream"#include <stack>using namespace std;
struct node{

    int item;
    struct node *left;
    struct node *right;
};

class bst{

    private:
         struct node *root;

    public:


    struct node* insert_node(node *root,int item)
    {
      if(root == NULL) {
          root = new node;
          root->item = item;
          root->left = NULL;
          root->right = NULL;
      }

        else{

          if(root->item< item)
          {
            root->left =  insert_node(root->left,item);
          }
          else if(root->item >item)
          {
             root->right = insert_node(root->right,item);

          }
      }

        return root;

    }

    /*Method to print inorder traversal of a BST*/   
 void inorder(node *root)
    {
        stack<node*> stack;
        node *curr=root;
        while(!stack.empty() || curr!=NULL)
        {
            /*If current node is not NULL push the node in stack*/            
           if(curr!=NULL)
            {
                stack.push(curr);
                curr=curr->left;
            }
                /*If current node is empty or NULL pop it from the stack */           
           else           
            {
                curr=stack.top();
                stack.pop();
                cout<<curr->item<<" ";
                curr=curr->right;
            }
        }
    }





};



int main()
{
    bst tree;
    struct node *root = NULL;
    root = tree.insert_node(root,1);
    tree.insert_node(root,2);
    tree.insert_node(root,13);
    tree.insert_node(root,4);

    tree.inorder(root);

}