Wednesday, June 12, 2013

Using libssh2 on multithread code.


Day1.

I have a daemon running on CentOS4.3. By the way, an operator told me that the server it resides should be moved to the other rack. So I decided to move and upgrade OS version to CentOS6.3 with gcc-4.4.6 during migration. I moved and compiled. But it stopped after several minutes. The daemon spawns many threads and each thread has socket connected via boost::asio. Each thread passes connected socket to libssh2_session_handshake() for ssh connection. Libssh2 library is used here. It uses libgcrypt library to generate 16 bytes of random numbers. However, gdb didn't show call stack when it goes into library routine(showed function name like ???() ). To know where it stops, I downloaded each libraries(libssh2, libgcrypt, libgpg-error) and compiled them again. Gdb finally showed that libgcrypt tries to attain mutex lock to access random pool for generating random number, it stops because it designed to fail to get mutex lock and assert. It works well on single thread environment. This isn't typical way to use libssh2 library. No helpful answer found at Google... TT.

Day2.

After doing more googling, bingging I found interesting information. Acturally both libssh2 and libgcrypt are designed for multithread environment. There was nothing to do for libssh2 to run it on MT-ed code. But something should have been done for libgcrypto. Because it doesn't know which thread mechanism is used in the host, it implemented two types of structures and functions for mutex as a macro. One for pthread and the other for pth. So the application code that I'm managing should select which macro to be used by adding following lines before it forks thread(pthread selected).

#include <gcrypt.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;

And it also should call gcry_control() so that the library assign callbacks to each functions related to mutex it uses like below.

gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

Several day has passed, and the server works well up to now. Hooray! :)

Thursday, March 28, 2013

How to check if a value is NaN in C++


I didn't know until now that if (a != a) returns true only when a is NaN.


#include <iostream>
#include <cmath>

using namespace std;

int main() {
    float a = sqrt(-1); // nan
    if (a != a) {
        cout << "It's NaN!" << endl;
        cout << a << endl; // prints 'nan'
    }
    else {
        cout << "It's OK!" << endl;
    }
    return 0;
}

Friday, November 23, 2012

Python threads with queue.

import threading
import Queue

import urllib2
import time
                
urls = ["http://www.google.com", \
    "http://www.naver.com", \
    "http://www.daum.net"]
    
queue = Queue.Queue()
        
class CustomThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            task_url = self.queue.get()
            start = time.time()
            page = urllib2.urlopen(task_url)
            end = time.time()
            print """%s elapsed %s (from %s)""" \
                % (task_url, end - start, self.getName())
            self.queue.task_done()

def main():
    for i in range(2):
        t = CustomThread(queue)
        t.daemon = True
        t.start()

    for task_url in urls:
        queue.put(task_url)

    queue.join()

    print "Ended"

if __name__ == "__main__":
    main()


This is typical producer-consumer model using queue. We can use this model when we want to keep threads running on though tasks are consumed up(like threadpool). Otherwise, we can call join() for each thread instead of calling queue.join().

Thursday, August 16, 2012

Dustin Hyun at NHN Corporation.

I was interviewed to be posted on corporate blog of nhn(written in Korean).

http://naver_diary.blog.me/150144134830


NHN PEOPLE - 2. 개발자

NHN에서 가장 많은 사람은? 당연히 개발자입니다. NHN 직원 중 절반 이상이 개발자입니다. 게다가 인터넷 서비스에 필요한 소프트웨어는 워낙 다양하기 때문에, 개발자들이 담당하는 역할도 천차만별입니다. 이번 시리즈를 준비하면서 다양한 개발직군의 모습을 보여 드리고 싶었는데요. NHN PEOPLE 두 번째 주인공 현동석 차장은 그 좋은 예가 될 것 같...





Friday, May 25, 2012

Good explanation on linux daemon.

I was programming a daemon invoked from a python script which is also invoked from a server that fork() .py when it gets a command through TCP connection.

TCP:Message => Server:fork() => python:os.system() => daemon(c++)

However, server couldn't return the message from python script even though the binary was demonized successfully(It was a zombie proccess).

I spent a lot of time to find for this. TT. I found that the daemon inherited all file descriptors from the server via .py script.

Now everything works find after closing all fds after being fork()ed.

Useful links:
http://www.enderunix.org/docs/eng/daemon.php

Friday, June 24, 2011

Recording Desktop at Ubuntu

Very simple.

Record with gtk-RecordMyDeskTop. Outfile format will be .ogv

To convert ogv to avi,

> mencoder -idx out.ogv -ovc lavc -oac mp3lame -o out.avi

Done.

Monday, June 13, 2011

C++: Building custom vector class.


Making custom container class with iterator would be a good example for C++ beginner.




Vector.h


#ifndef VECTOR_H
#define VECTOR_H

#include <vector>
#include "VectorIterator.h"

class Vector {
public:
    typedef VectorIterator iterator;

    Vector(int size) { data_.resize(size); }

    int size() const;
    void push_back(const int val);

    VectorIterator begin();
    VectorIterator end();

    int& operator[](const int& idx);
private:
    std::vector<int> data_;
};

inline int &
Vector::operator[](const int& idx) {
    return data_[idx];
}
inline int
Vector::size() const {
    return data_.size();
}

inline void
Vector::push_back(const int val) {
    data_.push_back(val);
    return;
}

#endif /* VECTOR_H */


Vector.cpp


#include "Vector.h"

VectorIterator
Vector::begin() {
    return VectorIterator(&data_);
}

VectorIterator
Vector::end() {
    VectorIterator vec(&data_);
    vec.setIndex(data_.size());
    return vec;
}


VectorIterator.h


#ifndef VECTORITERATOR_H
#define VECTORITERATOR_H

#include <vector>

class VectorIterator {
public:

    VectorIterator();
    VectorIterator(std::vector<int> * data);

    void setIndex(int v);
    int operator*();
    int operator++();
    bool operator==(const VectorIterator& rhs) const;
    bool operator!=(const VectorIterator& rhs) const;
private:
    std::vector<int>* pvec_;
    int index_;
};

inline int
VectorIterator::operator*()
{
    return (*pvec_)[index_];
}

inline int
VectorIterator::operator++()
{
    index_++;
    return (*pvec_)[index_];
}

inline bool
VectorIterator::operator==(const VectorIterator& rhs) const
{
    return (pvec_ == rhs.pvec_ && index_ == rhs.index_);
}

inline bool
VectorIterator::operator!=(const VectorIterator& rhs) const
{
    return !(*this == rhs);
}
#endif /* VECTORITERATOR_H */


VectorIterator.cpp


#include "VectorIterator.h"

void
VectorIterator::setIndex(int v) {
    index_ = v;
    return;
}

VectorIterator::VectorIterator()
    : pvec_(NULL), index_(0) {}

VectorIterator::VectorIterator(std::vector<int> * data)
    : pvec_(data), index_(0) {}



main.cpp


#include <iostream>
#include "Vector.h"

int main()
{
    int size = 10;
    Vector vec(size);

    for (int i = 0; i < vec.size(); i++)
        vec[i] = 2 * i;

    for (Vector::iterator iter = vec.begin();
        iter != vec.end(); ++iter)
        std::cout << *iter << std::endl;

    return 0;
}