Generalized Producer-Consumer solution using Semaphore

The producer-consumer problem is a classical example of a multi-process synchronization problem. It illustrates the need for synchronization in systems where many processes share a resource. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer. The producer's job is to generate a piece of data, put it into the buffer and start again. At the same time the consumer is consuming the data (i.e. removing it from the buffer) one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.

Here, the problem is generalized to have multiple producers and consumers. The solution to these type of problem must assure three constraints
  1. Mutual exclusion
  2. Free from Deadlock
  3. Free from Starvation
Pseudo-code for the solution to multiple producer- consumer problem is given below.

Semaphore fullBuffer = 0; // Initially, no item in buffer
Semaphore emptyBuffers = numBuffers; // Initially, num empty buffer
Semaphore mutex = 1; // No thread updating the buffer
Producer(item) {
emptyBuffers.P(); // Wait until space
mutex.P(); // Wait until buffer free
Enqueue(item);
mutex.V();
fullBuffers.V(); // Tell consumers there is data in buffer
}
Consumer() {
fullBuffers.P();
mutex.P();
item = Dequeue();
mutex.V();
emptyBuffers.V();
return item;
}
The mutex lock is used to ensure that only one process will be accessing the buffer at a time,this protect the Queue data structure (a shared buffer) from being damaged. If the mutex lock is not used then the concurrent process can manipulate the head and tail pointer associated with the buffer in undesired way. The emptyBuffers and fullBuffer are the semaphore specifying the no of the empty buffers and fullbuffer available respectively.

The code implementing the given pseudo-code is shown below:

/*
* main.c
*
* Created on: Dec 31, 2008
* Author: Suvash Sedhain
* Multiple producer and Multiple consumer solution using Semaphores
* Note: semaphore.P() is actually sem_wait() and semaphore.V() is sem_post()
* as defined in semaphore.h
*
* Ref:
* - Operating System Concepts : Abraham Silberschatz, Peter Baer Galvin, Greg Gagne
* - Operating Systems, William Stallings
* - Professor John D. Kubiatowicz lectures notes, University of California, Berkeley
* website: http://inst.eecs.berkeley.edu/~cs162
*
*/

#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFER_SIZE 5
const int MAX_PRODUCER = 20;
const int MAX_CONSUMER = 20;

// information to maintain the circular queue data structure
int head = 0;
int tail = 0;

//shared buffer
int buffer[BUFFER_SIZE];
// mutex lock for buffer
pthread_mutex_t mutex;
//semaphores for specifying the empty and full
sem_t emptyBuffers;
sem_t fullBuffer;

//initialze the locks
void initialize_locks()
{
pthread_mutex_init(&mutex,NULL);
sem_init(&emptyBuffers,0,5);
sem_init(&fullBuffer,0,0);
}

// Produce random value to shared buffer
void *producer(void *param)
{
int item;
while(1)
{
item = rand();
sem_wait(&emptyBuffers);
pthread_mutex_lock(&mutex);
buffer[tail] = item ;
tail = (tail+1) % BUFFER_SIZE;
printf ("producer: inserted %d \n", item);
fflush (stdout);
pthread_mutex_unlock(&mutex);
sem_post(&fullBuffer);

}
printf ("producer quiting\n"); fflush (stdout);
}

//consume values from the shared buffer
void *consumer(void *param)
{
int item;
while (1)
{
sem_wait(&fullBuffer);
pthread_mutex_lock(&mutex);
item = buffer[head];
head = ( head + 1) % BUFFER_SIZE;
printf ("consumer: removed %d \n", item);
fflush (stdout);
pthread_mutex_unlock(&mutex);
sem_post(&emptyBuffers);
}
}

int main( int argc, char *argv[])
{
int i, sleep_time = 100, no_of_consumer_threads = 10, no_of_producer_threads = 2;
pthread_t producer_id[MAX_PRODUCER], consumer_id[MAX_CONSUMER];
initialize_locks();
// create producer threads
for(i = 0; i < no_of_producer_threads; i++)
{
if (pthread_create(&producer_id[i],NULL,producer,NULL) != 0)
{
fprintf (stderr, "Unable to create producer thread\n");
return -1;
}
}
// create consumer threads
for(i = 0; i < no_of_consumer_threads; i++)
{
if (pthread_create(&consumer_id[i],NULL,consumer,NULL) != 0)
{
fprintf (stderr, "Unable to create consumer thread\n");
}
}
sleep(sleep_time);
return 0;
}

Simple RSS feed reader in python

Writing a simple RSS feed reader is pretty simple in python.Here i have presented a simple snippet that prints the "title" element of the RSS feed

# This program is free software; you can redistribute it and/or modify

# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.


from urllib2 import urlopen
from xml.sax import make_parser, ContentHandler
import sys

__author__ = "Suvash Sedhain"
__date__ = "Fri Sep 12 16:46:44 NPT 2008"

class RSSHandler (ContentHandler):

def __init__(self):
ContentHandler.__init__(self)
self.__inItem = False
self.__inTitle = False

def characters(self,data):
if self.__inTitle:
sys.stdout.write(data)

def startElement(self, tag, attrs):
if tag == "item":
self.__inItem = True
if tag == "title" and self.__inItem:
self.__inTitle = True

def endElement(self, tag):
if tag == "title" and self.__inTitle:
sys.stdout.write("\n")
self.__inTitle = False
if tag == "item":
self.__inItem = False

def listFeedTitle(url):
infile = urlopen(url)
parser = make_parser()
parser.setContentHandler(RSSHandler())
parser.parse(infile)

#extract all the python related links from dzone
listFeedTitle("http://www.dzone.com/links/feed/search/python/rss.xml")

Code Explanation:

The class RSSHandler is derived from the class ContentHandler, which is a interface that provides functionality of Parsing XML. we override methods characters, startElement and endElement to customize the parser as per our need.

The method invocation can be summarized as:
  • "characters" method is called when stream of text is encountered
  • "startElement" method is called when any starting tag is encountered
  • "endElement" method is called when any ending tag is encountered
The function make_parser is a factory function that returns the generic XML parser.

IMAGE VERIFICATION WITH PHP

Image verification has become an integral part in any online registration process. It is important to know whether the other side that is filling the form is really a human or any robot or automatic scripts so, its time to look at how it really works.


To achieve this with PHP, you need to have the GD library installed. The whole procedure is quite simple. You generate a random number and then stamp it over a picture and there you go, you have your own verification number on a nice picture.


The coding is also quite simple as the algorithm mentioned above. Enough of words and let’s take a look at the coding to make the things go clear.



//verification.php



$alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";



// generate the5 digit verification code


$rand = substr(str_shuffle($alphanum), 0, 5);



//create image from a given jpeg to write our code


$image = imagecreatefromjpeg("background.jpg");



//allocate the text color of the code


$textColor = imagecolorallocate($image, 0, 0, 0);



// write the code on the background image


imagestring ($image, 5, 5, 8, $rand, $textColor);



// send the content type header so the image is //displayed properly


header(‘Content-type: image/jpeg’);



// send the image to the browser


imagejpeg($image);



// destroy the image to free up the memory


imagedestroy($image);


?>


Save the above code as verification.php and preview it in your browser and there you have it.



How it works


In the above program, we created a string of alphanumeric characters. Then the sting was shuffled using str_shuffle(string) function. We then extracted the first five characters of the shuffled string using the substr(string,starting_position,no_of_chars). The extracted characters were then stored as our random code. We then created a image from the given image and wrote our code on the image using the imagestring(image,font,x_pos,y_pos,string,string_color). (Refer the imagettftext() function for better result).


And finally the image was fed to the browser using the imagejpeg(image) function for jpeg image. For a complete reference on the functions used in above codes, you can log on to the official site of php,


http://www.php.net/ and get your copy of php manual for free.



Now you have your verification code, but what about using it to verify the users. They say life is full of options and so does php offers a variety of options to pass a variable between the web pages. You can pass the random code generated to any other page either using sessions or cookies variables, using the form submission method or the rather insecure URL method. Let’s try it using session variables. For this you need to have some modifications on your verification.php file or whatever you named it. first of all initialize a session and then assign the random number to a session variable.


//mod_verification.php



Session_start();



$alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";



// generate the5 digit verification code


$rand = substr(str_shuffle($alphanum), 0, 5);



//assign session variable the verification code


$_SESSION[‘variable’]=$rand;



//create image from a given jpeg to write our code


$image = imagecreatefromjpeg("background.jpg");



//allocate the text color of the code


$textColor = imagecolorallocate($image, 0, 0, 0);



// write the code on the background image


imagestring ($image, 5, 5, 8, $rand, $textColor);



// send the content type header so the image is //displayed properly


header(‘Content-type: image/jpeg’);



//save the final image as image.jpg


imagejpeg($image,”image.jpg”);



echo “<img src=\”image.jpg\”>”;;



echo "Type the code you see in the image in the box below. (case sensitive)";



?>




<form action=check.php method=post>





<input name=code type=text > //place to type the code



<input type=submit> //submit button




</form>







With that done, we must now create a new file and name it check.php and see if it works.



//check.php



Session_start();



//retrieve the posted variable via forn


$typed=$_POST[‘code’];



//retrieve the session variable


$var=$_SESSION[‘variable’];



echo “The verification code was $var and you typed $typed”;



if($var==$typed)


{


echo “you are verified”;


}



?>




There you are, with your own image verification tool.



5 Reasons why beginner hates web-frame work?

Working on spring framework and Cake PHP framework make me realize why beginners hate web-framework. I had heard a lot of eulogy about spring so I was eager to use the spring framework. Initially, I found the framework enigmatic. Aspect Oriented programming, Dependency injection, Bean creation, Validation and Hibernate everything was completely new for me. At first, to create a simple “hello world” was also daunting task for me. Fortunately, my team leader was expert in all those things and he was so helpful. So, we keep on learning all those stuffs during the course of the project. Now, I am working with energetic programmers on CakePHP framework. As I am familiar with MVC, Cake PHP is yummy for me. Although my teammates were familiar with PHP but MVC was new for them. So, at the beginning they were arguing “Why we are using any framework?” And they were not convinced about the productivity of the framework too.

As per my personal experience, following are the 5 reasons why beginner hates web-framework

1) Comparing everything with hello world.

I have found in many pages which compares languages by showing in how many line they can display “hello world” and something simple things like this. I have found the good impression of such pages on the beginner. So, when I say you need MODEL, VIEW and CONTROLLER to create a simple app to a beginner, they simply think that frame-work adds overhead because they have to create three pages to create a simple hello world.

2) Coding Convention

While working with the Cake PHP naming convention of the model view and controller have annoyed my team members and it reminds me the days when novice to the spring frame work.

3) Functionality provided by the framework

Beginners prefer to use their own code even though the framework provides it. Once,

One of my teammates argued with me regarding the CakePHP validation. At first he used his own JavaScript based validation. But After working with numbers of pages he realized that it’s effective to use the CakePHP validation and was convinced to use that.

4) MVC is overhead for beginner.

Actually MVC systematize the development process itself. Work of the programmer and designer can be easily separated. So, coding and designing can go hand on hand. Its difficult for the beginner to visualize the program flow with MVC. However, it is difficult to convince the beginner about MVC pattern until and unless they get involved in any large projects.

5) Framework is difficult to understand.

For any one who is new to any framework, s/he has problem on even in simple things. Only difference is that for the people who have already worked in other frameworks can compare the features and quickly learn the things. But, for the novice it is too difficult to grasp a lot of new terminology at a time. So, all these terminology intimidate the novice.

Object Oriented Programming with PHP

The term object-oriented involves thinking about processes as entities; in other words, the way we think about day-to-day objects. Object oriented programming is widespread today, and many universities teach object-oriented programming in beginning programming classes. Currently, Java and C++ are the most prevalent languages used for object-oriented programming. Object-oriented programming is not just a matter of using different syntax. It’s a different way of analyzing programming problems. In object-oriented programming, the elements of a program are objects. The objects represent the elements of the problem your program is meant to solve. Object-oriented programming developed new concepts and new terminology to represent those concepts.

But what about OOP in web scripts like PHP? Web scripts typically execute quickly and then go away. So you may think do we really need OOP concept in the web scripting? PHP wasn’t developed as an object oriented language. PHP began life as a simple set of scripts. However, PHP couldn’t be left untouched by this growing global phenomenon of OOP and its numerous advantages forced it to be reckoned by the language. Over the course of its life, PHP has evolved, more and more object-oriented features. First, you could define classes, but there were no constructors. Then, constructors appeared, but there were no destructors. Slowly but surely, as more people began to push the limits of PHP's syntax additional features were added to satisfy the demand. Object oriented programming became possible with PHP 4. With the introduction of PHP 5, the PHP developers have really beefed up the object-oriented features of PHP, resulting in both more speed and added features. Much of this improvement is invisible — changes introduced with the Zend 2 engine that powers PHP 5, that make scripts using objects run much faster and more efficiently than they did in PHP 4. PHP typically has a less thoroughgoing implementation of OOP than languages like c++, java, etc. There are still some concepts missing as function overloading and multiple inheritances.

OOP concept has really changed the way we used to program in PHP. Because of OOP, the code redundancy has been greatly reduced and using this technique we are able to make simple programs on the fly. This concept has helped to develop and maintain large scale projects easily. Features like inheritance, encapsulation and abstractions have helped speed up the development process of products using PHP. As of PHP5, it supports single inheritance, constructors and destructors, encapsulations, static functions, object interface, etc. So, OOP is certainly developing as an integral part of PHP programming.

Tech News

Loading...