15 March, 2014

Getting Started with Go: A Systems Programming Language for the Modern Era

 

Introduction

The programming landscape is constantly evolving, with new languages emerging to address the limitations of existing ones. In recent years, one language has been gaining significant traction among systems programmers and web developers alike: Go (or Golang). Developed at Google by Robert Griesemer, Rob Pike, and Ken Thompson, Go aims to combine the efficiency and safety of statically typed compiled languages with the simplicity and productivity of dynamic languages.

As someone who has worked extensively with C++ and Java, I've found Go to be a refreshing alternative that addresses many pain points associated with traditional systems programming languages. In this article, I'll introduce you to Go's key features, compare it with established languages, and demonstrate its capabilities through practical examples.

The Origins and Philosophy of Go

Go was born out of frustration with the complexity and verbosity of languages like C++ and Java, combined with the need for better concurrency support in an increasingly multi-core world. The language was officially announced in 2009 and reached version 1.0 in 2012, marking its stability for production use.

The philosophy behind Go can be summarized in a few key principles:

  • Simplicity: Go has a small language specification with minimal syntax
  • Readability: Code should be easy to read and understand
  • Pragmatism: Focus on solving real-world problems
  • Concurrency: Built-in support for concurrent programming
  • Efficiency: Fast compilation and runtime performance

These principles inform every aspect of Go's design, from its streamlined syntax to its approach to memory management.

Key Features of Go

Static Typing with Type Inference

Go is statically typed, meaning types are checked at compile time. However, unlike languages like Java or C++, Go often doesn't require explicit type declarations thanks to its type inference system:

In Go, you can declare variables with explicit types: var message string = "Hello, Go!"

Or you can use type inference for more concise code: message := "Hello, Go!"

This gives developers the safety of static typing without the verbosity.

Fast Compilation

One of Go's most impressive features is its compilation speed. Go was designed from the ground up for fast compilation, with a dependency management system that minimizes the work needed during incremental builds.

On my development machine, a medium-sized Go project typically compiles in seconds, compared to minutes for similar C++ projects. This rapid feedback loop significantly improves developer productivity.

Built-in Concurrency

Go's approach to concurrency is perhaps its most revolutionary feature. Rather than relying on threads and locks, Go introduces two key concepts:

  1. Goroutines: Lightweight threads managed by the Go runtime
  2. Channels: Type-safe pipes that allow goroutines to communicate

Here's a simple example that demonstrates concurrent execution:

A simple concurrent program in Go would look like this:

package main

import "fmt" and "time"

First, define a function that prints messages:

  • Function sayHello(id int) that loops 5 times
  • Prints a message with the goroutine ID and current index
  • Sleeps for 100 milliseconds between iterations

In the main function:

  • Start two goroutines with the "go" keyword (go sayHello(1) and go sayHello(2))
  • Wait for the goroutines to finish by sleeping for 1 second
  • Print "Main function completed"

When run, this program would show interleaved messages from both goroutines, demonstrating their concurrent execution.

This program launches two goroutines that run concurrently, each printing messages at intervals. The output will show interleaved messages from both goroutines, demonstrating their concurrent execution.

Garbage Collection

Go includes a garbage collector that automatically manages memory, freeing developers from manual memory management. While garbage collection typically introduces performance overhead, Go's GC is designed to minimize pauses and interference with running programs.

Standard Library

Go ships with a comprehensive standard library that covers everything from low-level networking to cryptography and compression. The standard library is well-documented, consistent, and focused on practical use cases.

Go vs. Other Languages

Go vs. C/C++

Coming from C++, I immediately appreciated several aspects of Go:

  1. Simpler syntax: No header files, class hierarchies, or template metaprogramming
  2. Memory safety: No pointer arithmetic or manual memory management
  3. Faster compilation: Orders of magnitude faster than C++
  4. Built-in concurrency: No need for complex threading libraries

However, Go does give up some features that C++ programmers rely on:

  1. No generics (as of Go 1.0): Requires interface-based programming or code generation
  2. Limited low-level control: No direct memory manipulation
  3. No operator overloading: Can lead to more verbose code for mathematical operations

Go vs. Java

Compared to Java, Go offers:

  1. Lighter weight: No JVM required, smaller runtime
  2. Faster startup: Compiled to native code
  3. More explicit error handling: No exceptions, using returned error values instead
  4. Simpler object model: No inheritance, just composition and interfaces

Java still has advantages in certain areas:

  1. Richer ecosystem: More mature libraries and frameworks
  2. Better tooling: IDEs and development tools are more advanced
  3. Generics support: More type-safe collections and algorithms

Building a Simple Web Server

Let's demonstrate Go's capabilities by building a simple HTTP server that responds with "Hello, World!":

A simple web server in Go would consist of:

package main

import statements for "fmt", "net/http", and "log"

A handler function that writes a response:

  • Function helloHandler that takes response writer and request parameters
  • Uses fmt.Fprintf to write "Hello, World!" to the response

In the main function:

  • Register the handler function for the "/hello" path
  • Print a message indicating the server is starting
  • Start the HTTP server on port 8080
  • Check for errors and log them if they occur

This code demonstrates Go's built-in HTTP capabilities without requiring external frameworks.

This example demonstrates several Go features:

  1. The concise import system
  2. Function declaration syntax
  3. Error handling pattern
  4. Built-in HTTP server from the standard library

To run this server, save the code to a file named server.go and execute:

go run server.go

Then navigate to http://localhost:8080/hello in your browser.

Getting Started with Go

If you're interested in trying Go, here's how to get started:

  1. Install Go: Download the installer from golang.org
  2. Set up your environment: Configure GOPATH as described in the documentation
  3. Write your first program: Create a file named hello.go with the following content:

A minimal "Hello World" program in Go:

package main

import "fmt"

func main() { fmt.Println("Hello, Go!") }

  1. Run your program: Execute go run hello.go
  2. Explore the documentation: Go has excellent documentation at golang.org/doc

Conclusion

Go offers a compelling alternative to traditional systems programming languages, combining performance, safety, and simplicity. Its straightforward syntax and powerful concurrency model make it particularly well-suited for networked services and distributed systems.

As a relatively young language, Go is still evolving, with an active community and growing ecosystem. While it may not be the right choice for every project, its pragmatic approach and focus on developer productivity make it worth considering for your next systems programming or web service task.

In future articles, I'll explore more advanced Go topics, including testing strategies, package management, and best practices for building production-ready applications. Stay tuned!


About the author: I'm a software engineer with experience in systems programming and distributed systems. After working extensively with C++ and Java, I've been exploring Go for building high-performance web services and microservices.

06 September, 2013

Back....

Hello World,

Its been a while. I was busy working with Polycom as a Software Developer Intern in a product called Millennium - 360 degree panoramic 1080p video solution which would hit the market shortly. Hopefully everything goes well.

Alrighty... So what I got now..I came across one thing recently which I thought I would share.

So everyone would have used wikipedia atleast once. So how do you print a wiki article?

Open the wiki page  -> Chose Print option from web browser ? Is that what you think...
Won't the pages look disordered with images scattered and contents not justified properly......
What if you want to combine many wiki articles and take printout?
 Do you download all html pages and print each page? Isn't this annoying?

So wiki has come up with this ( I'm not sure when it was ) concept called "Book Creater".
If you had already known about this, there is nothing new I'm gonna tell.
For those who doesn't know about it, go on.

Goto wikipedia.org main page (http://en.wikipedia.org/wiki/Main_Page)
Under Print/Export in left pane, chose create a book -> Start book creater.
Now you can visit any wiki pages you want and add to your book. At the end, this can be downloaded as a pdf which can be later printed or you can read it using your gadgets. Cool isn't it :)

This is such a nice feature which I didn't know earlier :)
Anyways, hope you can make use of this cool stuff.
Take care guys.  Will come up with articles as and when I learn new things or something strikes my mind.

17 April, 2013

Self Modifying Code

Sorry guys. It's been a while. I'm near the end of Spring Semester with hectic things ahead.
In the mean time, I thought I would post something for us to chew.

Okay this post is about Self Modifying Code which I came across recently in my course work
where there was a line "The issues with Binary Translation (VMM) is Self Modifying Code".

 Lets not look into VMM aspects, rather I shall restrict myself to the later.

What is Self Modifying Code?

Program that purposely alters its own instructions while executing.
Something like a chameleon :-)

If we write a code that improperly manipulates a buffer then its a self modifying code :-) leading to crash.

Questions arise as to why we need this kind of code for which I would suggest to read the wikipedia article for its usages.

Of-course one can use this to create viruses ! making life difficult for anti-virus programs / honeypots.

It is not the code that gets changed [ Of course it needs to :-) ] but the executable that needs to change while its running. This restricts us to OS specific.

Say suppose we have a program emitting some output. Now lets open the executable using
hex editor, modify the executable to emit a different one.

If we see windows updates, its evident that program which is in execution is closed, re-written and started again. Can't this be done while the program is in execution?

Consider a huge deployment where there is a small bug with respect to your component.
The fix is just adding a check or changing some macro.

Instead of rebuilding the entire component,  is it possible to write a small piece of code ( a function ) which could tweak into image of running file and fixes the bug by altering it.
This would be of great help. isn't it ? :-)

So how do we do it?  I'm also trying it.
In the mean time, you guys too can try.

Lets state our objective

a) We know the operating system where our "*.so || *.exe || *.sl" is running.
b) Our objective is to tweak this executable for a minor fix that was found in site deployment.
    [Note : we are not supposed to restart the process]

Have fun while trying :)

30 March, 2013

What is it like for an Indian student to pursue MS/PhD from a US university?

    Courtesy : Quora

    Before I answer this question, I would like you to know that I am not from one of the premier Institutes in India . What I say henceforth is largely from a view point of an average Indian pursuing his/her graduate studies in the United States. I will warn you that this is going to be a subjective analysis and more like I am venting out my frustration against fellow Indian students. I know I am likely to draw a lot of flak for this and may fetch comments like I should check out some of the top schools, but yeah well, I am in one of the top CS programs and things are no different from a 2nd tier school. You can only imagine the shock I felt.

    The American way of life.
    Folks here are largely individualistic. And I applaud them for being so. I might have seen only a niche group of Americans here, but I can safely conclude that they are polite, humble and most important of all, have this extreme passion for a godforsaken field that we, status loving, name dropping folks, are largely alien to. I know of a American teammate who is crazy about collecting motocross statistics and he is pretty serious about it . The passion is so infectious, it makes me go weak on my knees, to the point of being mistaken as someone experiencing a hot flush. No kidding. There is just no match to the passion these guys have.

    Point to be noted: They are one of the few groups that go on a vacation during Spring Break, mostly because they are disciplined with their work and manage their time well.
    .
    Occasionally, I do run into some whack-jobs who are anti-abortion or anti-gay, but that's a minuscule number and doesn't represent the whole. Americans in general are a private lot, love sports and take a great deal of pride in who they are and what they do.They could be running your local grocery store and they are mighty proud about it. Unlike us who look down upon anyone not a Computer Science Engineer or a Doctor, they are less pretentious and more open to failures. A Stanford graduate never talks about his pedigree because he knows what it is to be subtle and he knows that it is the idea that matters more than where the person is from. I appreciate this quality a lot and I only, only wish we, as a nation, embraced it.

    We all grew up in a place where there is so much noise about all things personal : grades, salary, property details to the precision of the last decimal point. That way, it is a breather here because almost all conversations with the non-Indian graduate students revolve mostly around their various hobbies, their interests, ideas and some dry humor. No one asks you whether you secured an internship or a job . They will never ask you your grades and will never question you if you are seen talking to someone from the opposite sex. Privacy, civility and respect is almost embedded into their culture as is lack of personal space and lack of sense of individuality in ours. I seldom hear them say "Oh well, when I was at Stanford, I got job offers from X , Y and Z!

    The Indian way of American life:

    The culture shock I experienced was from the Indian Community : There will be a certain 'Indian Student Association' in your graduate school. My two cents on this one. Run like Usain Bolt from them. Run as fast as you can. Their sole reason for existence is to display their 'accomplishments' in the pretext of on-boarding freaked out freshers like us. I could hear imaginary trumpets blaring when I got introduced to a couple of them. This is where your brainwashing begins and your starry eyed dream of an international experience begins to fade with the song-dance gala welcome party and samosas. And god forbid you are from the meek (elegant, I would say) southern part of India, you will probably receive 'light-hearted' racist comments about your 'Madrasi' idlis and sambhars. These are the same folks who extend their sincere support when one Mr.Khan gets questioned by the TSA and cry foul about how racism is rampant in the western world. These guys cannot differentiate Chennai from Bangalore from Hyderabad and even Orissa. Goodness gracious. I don't even want to comment on poor East-Indians. Double standards, not new right?

    Soon after, you will mail your Indian senior graduates asking them for suggestions on courses to choose, professors to work with, projects to work on, all with the primary intent of landing a plum job with a very well known firm. Things are often exaggerated (like the Indian weddings), you are scared the hell out if you dare go beyond the norm and pick courses that your senior friend brands as 'very difficult' by his standards. He will scare you SO much, that it reverberates all through your semester, your confidence taking a beating with every tiny mistake you make. And worse, you repeat the same cycle, plant this seed into another incoming student's head and there, you have an entire line of Indians not signing up for a course because, oh well, seniors did not take it. Indians here are risk averse, not because they are not capable of taking risks (a foreign graduate study is risk in itself) but because they are surrounded by a peer group that psychologically prevents them from taking risk. I hardly see them trying out something as unpredictable as a start-up or going for that arduous PhD that they dream of.
    Herd mentality has its victims. Not new to us, is it?

    You were perfectly capable of doing well in that subject till you decided to get that bloated advice from your senior friend. Trust yourself to make the right call here and pick courses that you are passionate about, not because your senior friend tells you that it is 'easy' or 'difficult' or worse, that not signing up for that course will not fetch you a job (This, by far, is the lamest advice I have heard from an Indian senior. Made me cringe)

    The other side of this affair, the dangerous one, here goes: There are a certain 'easy' courses in your curriculum. By easy, it means easy grades or a lenient professor. Well, before you know it's easy (takes a month to realize that) your Indian friends and their senior bum-chums would have ragged you on your incompetency for not signing up for an intellectually challenging course like they did. Here I am paying nearly all my life savings in tuition for a subject that everybody makes fun of. How does that feel? It feels bloody miserable that such black and white judgement process exist in a world class university and your peers do not let you enjoy what you are studying. Easy or difficult, it's the learning I enjoy more so than anything. Of course, you could always show the finger and move on, but it does become a little difficult when the peer group views you as an intellectual misfit. They are all out to prove their choices, decisions are far superior to yours. Sounds familiar?

    The great Indian hype : If you happen to have worked for the biggies back home, you are a superstar here. Your friends hype your work, when you yourself don't care a penny about it, suddenly everyone thinks you are a smart kid, and nasty comments like 'Well, you are the smart one, you will obviously crack this, it's a joke for you' will be spewed. And if you fail to crack it, the same group immediately writes you off, leaving you wondering if you signed up for this after all. I did not create the hype, I did not publicize my work, but here I am being made fun for failing something I did not even claim I could solve!

    Minor annoyance, the Facebook feed of your party-kid Indian friend : There is also this certain Indian group who are one of those misinformed college kids clicking endless pictures and doing endless check-ins at every happening and non-happening place in the city. They are another reason for you to cringe. Having never seen the US or been here once or twice on a family trip , they are this uber excited , hyper active social beings who make us all look like party kids, desperate for attention. There is a flood of photos of your wannabe Indian friend with an American/Ukranian/German/French guy/girl (Who cares! they are all a bunch of good looking white folks anyway!) every 10 minutes on your news feed. Believe me, it makes you immensely popular among your Indian friends, you become the talk of the town (your Indian group). It is pretty much like living in India.

    You, if you are one of those pitiable Indian student with a hefty loan and with the sole purpose of learning, with dreams and ambitions beyond a job, inclined to know more about the American way of life, the history, the politics, the culture, the people, will be left wondering if you accidentally landed in India. Worse, they will look at you with contempt if you make the slightest indication that you are not inclined to their way of life, you are different, and you want to be a part of a broader culture that emphasizes on individualism than the collective thinking we have been brought up to accept. If you follow the election primaries/ presidential elections, my suggestion is to keep it a secret and pretend you enjoy Bollywood songs when you are with your group. Helps to bond and make them feel home.

    Your friends are nosy. They want to know who you hang out with, your grades, who you stay with, if things are okay with your roommates, the white 'chick' you find hot, whether you managed to get an internship, if not, some unsolicited advice on how I should be prepared for an unpaid internship, your salary and your plans of securing a job after Master's and more unsolicited advice. The rat race repeats all over again, the very same reason why you left India.

    Academics
    Life is not as easy-peasy as those Facebook photos depict. It is a lot of work, actually. More like a correction facility for all the tardiness back in our undergraduate classes. You will be forced to wake up early, forced to sleep late, forced to think for every assignment, forced to feel miserable about your performance in term exams and forced to shut up about your grades. You will be forced to become more disciplined in life. This is why I wrote in the beginning that I am not from one of the premier Indian institutes, because those guys are probably used to such load. If you are an average student like me, you will wonder where you are going wrong, in spite of being one of the top students in your class back home. It was rote learning back there, it is not that way here. Not a day passed in the first couple of months where I did not wish that I had studied in the US since the very beginning.

    But, of course, there is an easy way out of this, something you must know by now, given how things work in India. You can always get your answers on the internet or by discussing them with your Indian friends beyond the permitted levels and break all the academic honesty rules. Rules are meant to be broken isn't it? That's how things are back home! And with the self-righteous attitude we have, we collectively look down on anyone caught for academic dishonesty, but pretty much do it ourselves. 'Hey let's work on this assignment' is the norm, even if it clearly states that collaboration is not allowed. Any guesses why the Indians score well and way above average? Here it is.

    I know I did drift from the main topic. Now back to your actual answer.You will do great if you are sincere with your work, if you have a desire to learn, if you are curious and if you don't let the above affect you much. As another post here highlights, professors are approachable (Indian professors alike), resources are aplenty and school will keep you busy enough to forget a lot of peer pressure I mentioned above.You can select courses from technical/non-technical departments alike, while you are majoring in say Computer Vision. It need not be always coherent, because a lot of us are here to explore.You are not expected to become a subject matter expert and specialize in something. It is recommended, not mandatory. I know of a professor who majored in Music in his undergraduate studies and went on to get his PhD in Computer Science. That is the flexibility this system offers. Awesome isn't it?

    If you are in one of the research schools, I recommend you to get a hang of the kind of research that goes on and think about how you could contribute your tiny little idea to the academia, no matter how nebulous it is. That said, there is nothing wrong in looking for a job (I too want to make my living) but do not let it become a priority, because you are here for graduate studies and jobs/internships are more or less a by-product of what you do here. Education is something very close to my heart and it does bother me personally when the whole purpose is diluted with unnecessary add-ons like what I mentioned above.


23 March, 2013

Nitty-Gritty Things - 1

In this blog lets talk about some nitty-gritty implementation stuffs.

Okay. So assuming the reader knows C/C++

a) How to add time restrictions to user input?

To elaborate, we know in C, the user input is read using scanf/getc/getchar and in C++ using cin object.

So our objective is to add some time limit so that user inputs the value before the timeout.

a) You can do by calling a script written in bash/python etc from C code and evaluate.
b) May be create a thread and fire the thread when timeout happens.

Is there any other way? <Think before scrolling down>
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/alarm.html

After reading the above links, I came up with this.

#include<stdio.h>
#include<unistd.h>

#define TIMEOUT 5
int main()
{
        int t_iTemp;
        while( alarm(TIMEOUT), ( t_iTemp = getchar() ) != EOF )
        {
                putchar(t_iTemp);
        }
        return 0;

}

This program waits for 5 secs. If user doesn't input anything, it exits else just echoes the input
and waits for next 5 secs.

The idea is simple i.e to generate a signal based on timer.
But the important takeaway is about alarm function.


Okay lets see one more.

b) Say you are developing a clock app. Now you will have conditions for hours,seconds,mins etc

The thing we will talk is how do you display 00 when the clock moves from 59 in case of mins/secs and 23 in case of hour.

When we think about it, its nothing but printing "00". But remember here we are talking about numbers :-)

What happens when you assign 00 to a integer and print it. It should be printing 0 instead of 00.
So how do you print an integer as 00. This is what we will be talking.

<Think before scrolling>
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
..
.
.
..
.
.
.

You can use a format specifier :D

int a = 00;
printf("%d",a) -> 0
printf("%02d",a) -> 00

However there are functions which can replicate a given number/character which is the takeaway.
Check the below link.
http://www.cplusplus.com/reference/iomanip/setfill/


 int hrs = 0;
 cout<<setw(2)<<setfill('0')<<hrs<<endl;

Hope you enjoyed reading and got something out of it.
Please post comments/suggestions(if any).

20 March, 2013

Performance metrics of Computer Systems - 1

When we think about evaluating the performance of a system, some things that comes to our mind are

a) Configuration and Flow that needs to be bench-marked.
b) Number of instances of node/server (1 or many ).
c) Duration of the task.
d) Tools that are gonna be used for analyzing and preparing report.
e) Existing benchmark report of the system for comparing the new data.


Let me give you my idea on each of the above aspects as well as my views on performance metrics of a system. Specifically let me discuss about "arriving  at benchmarks when we release the Version 1 of the software" in this blog.

consider a simple coin toss :)  Yeah its about probability and queuing :D
How are we going to measure the performance of this toss?
a) May be height travelled by the coin ?
b) Number of flips it makes? etc etc.

We use "laws of physics" as a tool to measure the performance metrics of the coin.

Now consider a system where messages are received, parsed and given to various components and sent back. This kind of system is called Open system.

There is one more type of system called Closed System. Interpret it to a CI machine where CI-coordinators submit jobs which in-turn is executed on a set of machines ( servers ) and returns back to idle state.

Our software (Version 1) can be open or closed. As we don't have any previous benchmarks for this software, we have to arrive at a theoretical bench-mark so that we are able to ascertain the practical measurements.

So how do we arrive at theoretical benchmarks?
Using Queuing models :-). Yeah its all maths buddy :D

For those who have taken a Queuing course, these things should not be new. Others please continue reading.

As we are used to event-driven programming, lets continue our thoughts using this.

What is event-driven programming?
Some events happen and based on the event we execute some tasks ( code ). After this may be the server goes to wait state to handle next set of events.

So lets define 4 set of events.
a) Customers / Messages arrive randomly (which we call Poisson arrivals)
b) Customers / Message wait in queue for getting processed.
c) They get processed. ( called exponential service times)
d) They leave the system ( our system memory allocs are put back to pool. )

Of-course there are certain systems where messages arrive at fixed time slots like burst ( Systems like ALOHA / Slotted ALOHA uses something like this. Other case may be where attacker is trying to send a burst message causing buffer overflows in network elements) or what not.

So having defined these events we can categorize our system ( software ) as M/M/N/K system.
First M denotes the arrival rate of messages into our system. Second M denotes the rate at which it is processed. N denotes the number of servers handling our messages and K denotes the system capacity.

Why do we have two M's ?
Aren't the messages going to be served in the order they arrive?

No. Most systems have some thing called classes similar to IntServ/DiffServ model where customers paying more are grouped into higher classes and have better experience while those pay low have lower experience comparatively.

Also consider the case where server is bombarded with lots of requests it can't handle. What can server do now ?

It can delay the person entering the system through some protocols like Stateless Cookie protocol
i.e if some one sends INVITE message in case of SIP protocol or SYN message in case of TCP the server handling it can send a reply asking him to solve a hardest puzzle/ calculating a hash which would take sufficient amount of time for the sender to compute and reply. In the mean time server clears the messages in its queue and is ready to accept new connections.

So we are deliberately delaying the customer entering the system. This happens with IRCTC [ Indian Railway Reservation Systems Servers :) ]

So coming back to our M/M/N/K model, this model has a set of predefined formulas through which
one can arrive at various metrics of system like throughput, delay, waiting time of customer(message), time spent by the message in the system etc.

Using these values along with the system parameters one can arrive at the theoretical bench-mark of a system and then use it to compare with practical data of our version1 software.
 
Let us conclude it for now. Other factors would be posted gradually.
Hope you got something out of this post.
Please post comments/feedback (if any).

15 March, 2013

My experiences with Thread safe code - 1

In this post, let me share my views and experiences about things to be done while coding in a distributed environment with respect to thread safety.

Persons who had taken a course on operating systems would be knowing about thread safe code. For those who doesn't know anything about it, as always let me give a gist.

What is thread?
Thread is a light weight process.

What is process?
A process is a program in execution.

For example : Consider microsoft word. When you open it, the process starts running i.e this program is in execution. This program has lots of features like spell check, auto correct etc which are independent threads running along with it.

In a single threaded process, only one flow of control exist.  The code executed by these processes  need not be thread-safe. In multithreaded programs, the same functions and the same resources may be accessed concurrently by several flows of control.

Let me explain thread-safeness  through an example.

Consider the case where there are group of people who come together to perform a particular task.
Each people has a role i.e they have some boundaries/memory which they don't cross.
Ex : Hadoop/GFS(Chubby)/Open Stack etc.

To illustrate still more, consider a bathroom.
Only one person can use it at a time. Other persons should wait for their turn.

A thread-safe code protects shared resources from concurrent access by locks. 
Thread safety concerns only the implementation of a function and does not affect its external interface.

For further info please read this.

So having defined some basics of thread safe function, let me share my experiences on it.

If you had read my previous post on design patterns , I would have spoken about something called service and session. I was writing a separate library in my previous concern where the objective was to provide some features like calculating current time and attaching to message based on customer specified version.

This library written would be loaded by the service using dlopen and would be accessed for each and every session. So for calculating the current time, I was looking for some system calls which would return me the time/date etc and I came across this function called localtime. I was happy, used it & finished my implementation and was waiting for code review comments from my technical lead.

To my shock, the implementation was not supposed to be done in the way I had done.
My usage was proper. I have used proper libc function which is a tested code.

But then why?

I missed seeing the below one in  the local time function.

/***********************
The function accesses the object pointed by timer.


The function also accesses and modifies a shared internal object, which may introduce data races on concurrent calls to gmtime and localtime. Some libraries provide an alternative function that avoids this data race: localtime_r.
***********************/
I should have used localtime_r function () . Why ?

Because there can be multiple parallel sessions running in the server and there is a potential chance of multiple sessions accessing this library at same time leading to corruption.
I was thankful as it was caught in review stage else it would have leaked after deployment.

So the lesson learnt from this

"If you are programming in a multithreaded environment and you are looking for system functions defined in libc kind of libraries, confirm whether it is thread safe or not and then use it".

However there are many others which i would post gradually. I just glossed over some things in this post.

Thanks for reading. Lets conclude it for now about my view/experience on writing thread-safe programs.

Please post any comments/suggestions so that I can improve.