Tag Archives: Programming

Producer/consumer using pthreads

Here I present a C-program to demonstrate the use of pthreads to solve the classical producer/consumer problem. The following (self-explaining) program makes use of pthread’s mutex & condition APIs to achieve synchronization between producer & consumer threads. The program implements a simplified version of the original problem : the producer increments (produces) an integer, a shared resource, while the consumer prints (consumes) it.


Consumer : "Hello I am consumer #140317330908928. Ready to consume numbers now"
Producer : "Hello I am producer #140317322516224. Ready to produce numbers now"
Producer : 1
Consumer : 1
Producer : 2
Consumer : 2
Producer : 3
Consumer : 3
Producer : 4
Consumer : 4
Producer : 5
Consumer : 5
Producer : 6
Consumer : 6
Producer : 7
Consumer : 7
Producer : 8
Consumer : 8
Producer : 9
Consumer : 9
Producer : 10
Producer done.. !!
Consumer : 10
Consumer done.. !!

Preprocessing Go programs

Preprocessor macros can be considered integral part of C/C++ programs. From inclusion of header files to controlling the build type (Debug-vs-NonDebug or Linux-vs-Win), macros play a very important role. For example, there are many advantages of having a debug build. Adding asserts, trace points and printing useful information helps developers gain insights of a (faulty) program. On the other hand, the program can easily be build without all these ‘extra’ debug-related-code (aka release build) by using a macro-processor along with other build tools.

So I thought, how about using this macro-processor to process a Go program? Now the question arises – Isn’t cpp (the macro-processor installed on my machine) general enough to be used to process Go programs? The following text from the manual page doesn’t seem to agree:

“The C preprocessor is intended to be used only with C, C++, and Objective-C source code. In the past, it has been abused as a general text processor. It will choke on input which does not obey C’s lexical rules. For example, apostrophes will be interpreted as the beginning of character constants, and cause errors. Also, you cannot rely on it preserving characteristics of the input which are not significant to C-family languages. If a Makefile is preprocessed, all the hard tabs will be removed, and the Makefile will not work.”

Nevertheless, I am giving it a shot.

So, here is a small Go program that contains a macro :

/* @file : demo.go.p */
package main

import "fmt"

func main() {

        fmt.Println("This is a sample program to demonstrate the use of",
                    "preprocessor in a Go program..")
#ifdef EXTRA
        fmt.Println("And this is the extra text printed only when EXTRA",
                    "is defined.")

Now, lets try to build/run this program with/without the EXTRA macro defined.

# with EXTRA undefined
$ cpp  -P -o demo.go demo.go.p | go run demo.go
This is a sample program to demonstrate the use of preprocessor in a Go program..

# with EXTRA defined
$ cpp -DEXTRA -P -o demo.go demo.go.p | go run demo.go
This is a sample program to demonstrate the use of preprocessor in a Go program..
And this is the extra text printed only when EXTRA is defined.

I am not sure if this idea is non-refutable, but so far it has managed to convince me.

Ajax with Golang

Lately, I thought of trying my hands on the classic Ajax alongside Go language. The requirement is to write a simple web server which sends ‘current timestamp’ to the requester every second. I have written a small program to do exactly the same. The Ajax part is taken care by jquery.

In order to see it in action, one needs to run it “go run tick-tock.go”. When the program is running, it essentially becomes a tiny web server listening to requests at port ‘9999’.

Now all you need to do is fire up a browser and raise a request to the tick-tock server: http://localhost:9999/time

Go is awesome. Isn’t it?

A barebone logger for Go

While working on a Go library, I was looking for an elegant solution for logging. After following many discussions on the forum, I came up with the following barebone which I think is decent performant and clean. Check it out!

package main

import (

type Logger struct {
        log_func func(string, ...interface{})

func do_log(fmt string, args ...interface{}) {
        log.Printf(fmt, args...)

func do_not_log(fmt string, args ...interface{}) {
        // Do nothing..

func (logger *Logger) init_logger(enable_log bool) {
        if enable_log == true {
                logger.log_func = do_log
        } else {
                logger.log_func = do_not_log

func main() {
        logger := new(Logger)

        // command line option
        enable_log := flag.Bool("enable_log", false, "Enable logging")


        logger.log_func("%s", "log me!")
        logger.log_func("%s", "log me again..!")


$ ./logger
$ ./logger –enable_log
2013/01/28 11:41:19 log me!
2013/01/28 11:41:19 log me again..!

Locating current position on map

HTML5 introduced new set of specifications which include geolocation APIs. Using them one can find the location of a device. While exploring it further, I found a simple Javascript program that neatly demonstrates the overall idea (references (i)). The following code has been modified a bit from the original one to make it more verbose.

  if(navigator.geolocation) {


      // success callback, where 'position' holds the found coordinates.
      function(position) {
      // Instantiate a Google Map's LatLng object using the position coordinates.
      initialLocation = new google.maps.LatLng(position.coords.latitude,
        Now 'initialLocation' can be used to place a marker on the map or
        other coordinates related stuff.

      // error callback, where 'positionError' holds various error related
      // attributes (see reference (ii) for details).
      function(positionError) {
      // log the error message
      console.log("Geolocation service failed. MSG: " + positionError.message);
      {maximumAge:Infinity, timeout:10000});

  // Browser doesn't support Geolocation
  else {
    console.log("Your browser doesn't support geolocation.");

i) https://developers.google.com/maps/articles/geolocation
ii) http://dev.w3.org/geo/api/spec-source.html

Go sorting, an example

I was recently trying to figure out a way to sort entries stored in a map using Golang. And then, I came across the “sort” package. It provides a Sort() function which can used to sort slices and user-defined collections.

func Sort(data Interface)

All you need is to define the functions listed under the Interface type.

Here is an example to demonstrate the same :

package main

import (

type keys []int

/* Definitions for all 'Interface' functions. */
func (k keys) Len() int           { return len(k) }
func (k keys) Less(i, j int) bool { return k[i] < k[j] }
func (k keys) Swap(i, j int)      { k[i], k[j] = k[j], k[i] }

func main() {
        var (
                k keys
                i int

        var varMap = map[int][]string{
                3: []string{"Harry"},
                1: []string{"Tom"},
                2: []string{"Dick"}}

        k = make(keys, 3)

        for key, _ := range varMap {
                k[i] = key


        for i = 0; i < len(k); i++ {
                fmt.Println(k[i], " : ", varMap[k[i]])

Output :
>  go run sort.go 
1  :  [Tom]
2  :  [Dick]
3  :  [Harry]

Multiline statements in Golang

As Golang (unlike C, C++, Java, etc.) frees a programmer from using semi-colon ‘;’ to terminate a statement, one might find it problematic to write a miltiline statement in Go.

Lets start with a quote :

“Like C, Go’s formal grammar uses semicolons to terminate statements; unlike C,those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them. “

So, based on my experience so far, here is a trick that I would suggest, one can break a line after “an operator”.

        result := a +
                b +
func add(a int,
        b int,
        c int) (result int) {
        result = a + b + c

Now coming to strings, they can we written in two ways.

1) Interpreted string literal :

        str := "Lorem ipsum dolor sit amet, consectetur adipisicing" +
               " elit, sed do eiusmod tempor\nincididunt ut labore " +
               " et dolore magna aliqua. Ut enim ad minim veniam," +
               " quis nostrud\nexercitation ullamco laboris ..."

2) Raw string literal :
For multiline strings, back quote ‘`’ can also be used with a couple of restrictions :
a) Any character is legal except back quote.
b) Escape sequences won’t be interpreted.

        str := `Lorem ipsum dolor sit amet, consectetur adipisicing 
                elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis
                nostrud exercitation ullamco laboris ...`

go go go…

Create static and shared libraries in Unix

Static Library
Lets first look at how static library can be created and used :

(a) Compile print.c to get an object file :
gcc -c print.c -o print.o

(b) Create a static library (archive) of the object file :
ar rcs libprint.a print.o

According to *nix norms, static library’s name should start with ‘lib’ and have ‘.a’ extension. ar is a unix tool to create, modify and extract from archives.

(c) Now compile main.c and link it statically to the library.
gcc -static main.c -L. -lprint -o statically_linked

$ ./statically_linked
hello world!

Shared Library
One of the most important things to note while creating shared libraries is the object files should be compiled with -fPIC option (position-independent code).

(a) gcc -fPIC -c print.c -o print.o

(b) gcc -shared -o libprint.so print.o

(c) gcc main.c -o dynamically_linked -L. -lprint

$ LD_LIBRARY_PATH=. ./dynamically_linked
hello world!

Note: Detailed explanation of the above used gcc switches can be found in gcc manual pages.

Singleton : Restrict instantiation of a class to one object

In order to achieve this, first thing which we need to do is make the class’s constructor private, which in turn will not allow any other class (outside) to create an abject of that class directly using the constructor. After this we can just define a getInstance method, which does the required two things:
1. Check how many objects of the class have been created.
2. Depending on (1) return an instance of the class.

Here is the code :

  @file : test.java

class Singleton {
  private static int counter=0;

  private Singleton() { //private constructor
    System.out.println("Object instantiated!");

  static Singleton getInstance() {
    if (counter < 1 ) { // to allow only 1 object creation.
      Singleton inst = new Singleton();
      counter ++;
      return inst;

    System.out.println("Can't instantiate further ..");
    return null;

public class test {
  public static void main(String str[]){
    Singleton ins1 = Singleton.getInstance();
    Singleton ins2 = Singleton.getInstance();
    Singleton ins3 = Singleton.getInstance();

Output :

$ java test
Object instantiated!
Can't instantiate further ..
Can't instantiate further ..