Monday, June 15, 2009

Semaphore - Linux Lab

Posted by Sarjukottapuram

SEMAPHORE
Theory
Semaphores are a programming construct designed by E. W. Dijkstra in the late 1960s. Dijkstra's model was the operation of railroads: consider a stretch of railroad in which there is a single track over which only one train at a time is allowed. Guarding this track is a semaphore. A train must wait before entering the single track until the semaphore is in a state that permits travel. When the train enters the track, the semaphore changes state to prevent other trains from entering the track. A train that is leaving this section of track must again change the state of the semaphore to allow another train to enter. In the computer version, a semaphore appears to be a simple integer. A process (or a thread) waits for permission to proceed by waiting for the integer to become 0. The signal if it proceeds signals that this by performing incrementing the integer by 1. When it is finished, the process changes the semaphore's value by subtracting one from it.
Semaphore is a variable that can take only the values 0 and 1, binary semaphore. This is the most common form. Semaphore that can take many positive values are called general semaphores.
The definition of P and V are surprisingly simple. Suppose we have semaphore variable sv. The two operations are defined as follows:
P(sv) – If sv is greater than zero, decrement sv, if sv is zero, suspend execution of this process.
V(sv) – If some other process has been suspend waiting for sv, make it resume execution. If no process is suspended waiting for sv, Increment sv.
Semaphores let processes query or alter status information. They are often used to monitor and control the availability of system resources such as shared memory segments.
POSIX semaphores are much lighter weight than are System V semaphores. A POSIX semaphore structure defines a single semaphore, not an array of up to twenty five semaphores. The POSIX semaphore functions are:
sem_open() -- Connects to, and optionally creates, a named semaphore
sem_init() -- Initializes a semaphore structure (internal to the calling program, so not a named semaphore).
sem_close() -- Ends the connection to an open semaphore.
sem_unlink() -- Ends the connection to an open semaphore and causes the semaphore to be removed when the last process closes it.
sem_destroy() -- Initializes a semaphore structure (internal to the calling program, so not a named semaphore).
sem_getvalue() -- Copies the value of the semaphore into the specified integer.
sem_wait(), sem_trywait() -- Blocks while the semaphore is held by other processes or returns an error if the semaphore is held by another process.
sem_post() -- Increments the count of the semaphore.
All POSIX semaphore functions and types are prototyped or defined in semaphore.h. To define a semaphore object, use
sem_t sem_name;
To initialize a semaphore, use sem_init():
int sem_init(sem_t *sem, int pshared, unsigned int value);
• sem points to a semaphore object to initialize
• pshared is a flag indicating whether or not the semaphore should be shared with fork()ed processes. LinuxThreads does not currently support shared semaphores
• value is an initial value to set the semaphore to
Example of use:
sem_init(&sem_name, 0, 10);
________________________________________
To wait on a semaphore, use sem_wait:
int sem_wait(sem_t *sem);
Example of use:
sem_wait(&sem_name);
• If the value of the semaphore is negative, the calling process blocks; one of the blocked processes wakes up when another process calls sem_post.
________________________________________
To increment the value of a semaphore, use sem_post:
int sem_post(sem_t *sem);
Example of use:
sem_post(&sem_name);
• It increments the value of the semaphore and wakes up a blocked process waiting on the semaphore, if any.
________________________________________
To find out the value of a semaphore, use
int sem_getvalue(sem_t *sem, int *valp);
• gets the current value of sem and places it in the location pointed to by valp
Example of use:
int value;
sem_getvalue(&sem_name, &value);
printf("The value of the semaphors is %d\n", value);
________________________________________
To destroy a semaphore, use
int sem_destroy(sem_t *sem);
• destroys the semaphore; no threads should be waiting on the semaphore if its destruction is to succeed.
Example of use:
sem_destroy(&sem_name);
________________________________________
Program
/* Program to demonstrate the usage of semaphore variable in controlling the access to specific resources.
* This program contains two functions which display their own messages.
* The display is suitably controlled by the use of semaphore variable.
* It is a program in which a semaphore variable is shared between the main function and a thread function.
* This module can be compiled using 'cc semaphore1.c -lpthread' and executed './a.out'
//inculsion part.
#include
#include
#include
//function prototype for the thread function.
void * display_function();
//global semaphore variable to be shared.
sem_t sem_var;
int main()
{
pthread_t tid;
pthread_attr_t attr;
int i;
//initialising the semaphore variable with an initial value 0 (third arguement.)
sem_init(&sem_var,0,0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_create(&tid,&attr,display_function,NULL);
for(i=0;i<5;i++)
{
printf("\n Displaying from the main function:\t%d\n",i+1);
//waiting for the resources.
sem_wait(&sem_var);
}
//destroying the semaphore variable.
sem_destroy(&sem_var);
}
void * display_function()
{
int i;
for(i=0;i<5;i++)
{
printf("\n***** Displaying from the thread function.:\t%d\n",i+1);
//releasing resources.
sem_post(&sem_var);
sleep(1);
}
}
SERIALISABILITY PROBLEM.
(By using Semaphore Variable)
Program
* This program uses a variable 'data' whose value is used by two thread function.
* But the condition is that when a function uses it no other function should use it.
* This problem is tackled by definig two thread function and suitably making them access it by the use of semaphore variable.
* This module can be compiled using 'cc semaphore2.c -lpthread' and executed './a.out'
//inculsion part.
#include
#include
#include
//prototype for thread functions.
void * thread_function1();
void * thread_function2();
//global variables.
int data=0,end=0;
//global semaphore variables.
sem_t sem_var;
int main()
{
pthread_t t1,t2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
sem_init(&sem_var,0,1);
pthread_create(&t1,&attr,thread_function1,NULL);
pthread_create(&t2,&attr,thread_function2,NULL);
while(end!=2)
{
}
printf("\n\t****** The value of DATA is:\t%d ******\n",data);
}
//definition of first thread function.
void * thread_function1()
{
int a;
printf("\nEntered into thread function:1\n");
printf("\nThread function:1 waiting to gain access\n");
sleep(1);
sem_wait(&sem_var);
printf("\nAccess gained by thread function:1\n");
printf("\nThread function:1 using the value of 'DATA' \n");
a=data;
a=a+1;
data=a;
sem_post(&sem_var);
printf("\nResources released by thread function:1\n");
end++;
}
//definition of second thread function.
void * thread_function2()
{
int b;
printf("\nEntered into thread function:2\n");
printf("\nThread function:2 waiting to gain access\n");
sleep(1);
sem_wait(&sem_var);
printf("\nAccess gained by thread function:2\n");
printf("\nThread function:2 using the value of 'DATA' \n");
b=data;
b=b+1;
data=b;
sem_post(&sem_var);
printf("\nResources released by thread function:2\n");
end++;
}

Thread - Linux Lab

Posted by Sarjukottapuram

Thread

Theory

Multiple strands of execution in a single program are called threads or thread is a sequences of control within a process.Thread proces include thread creation, termination, synchronization (joins,blocking), scheduling and process interaction.All threads within a process share the same addresss space.

A thread in computer science is short for a thread of execution. Threads are a way for a program to fork (or split) itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another, but in general, the way that a thread is created and shares its resources is different from the way a process does.

Multiple threads can be executed in parallel on many computer systems. This multithreading generally occurs by time slicing, wherein a single processor switches between different threads, in which case the processing is not literally simultaneous, for the single processor is only really doing one thing at a time. This switching can happen so fast as to give the illusion of simultaneity to an end user.

Threads are distinguished from traditional multi-tasking operating system processes in that processes are typically independent, carry considerable state information, have separate address spaces, and interact only through system-provided inter-process communication mechanisms. Multiple threads, on the other hand, typically share the state information of a single process, and share memory and other resources directly. Context switching between threads in the same process is typically faster than context switching between processes. Systems like Windows NT and OS/2 are said to have "cheap" threads and "expensive" processes; in other operating systems there is not so great a difference.

Thread Basics

• Thread operations include thread creation, termination, synchronization (joins,blocking), scheduling, data management and process interaction.
• A thread does not maintain a list of created threads, nor does it know the thread that created it.
• All threads within a process share the same address space.
• Threads in the same process share:

o Process instructions
o Most data
o open files (descriptors)
o signals and signal handlers
o current working directory
o User and group id

• Each thread has a unique:

o Thread ID
o set of registers, stack pointer
o stack for local variables, return addresses
o signal mask
o priority
o Return value: errno

• pthread functions return "0" if OK.

Thread Creation
Function call : pthread_create
int pthread_create(pthread_t*thread,pthread_attr_t*attr,void *(*start_routine) (void*),void *arg);

Arguments

->thread - returns the thread id.(unsigned long int defined in bits/pthreadtypes.h)
->attr-Set to NULL if default thread attributes are used.(else define members of the struct pthread_attr_t defined in bits/pthreadtypes.h). Attributes include:

• detached state(joinable? Default: PTHREAD_CREATE_JOINABLE.Other option:PTHREAD_CREATE_DETACHED)
• schedulingpolicy(realtime?PTHREAD_INHERIT_SCHED,PTHREAD_EXPLICIT_SCHED,SCHED_OTHER)
• scheduling parameter
• inheritsched attribute(Default:PTHREAD_EXPLICIT_SCHED,inherit from parent thread:PTHREAD_INHERIT_SCHED)

• scope(Kernelthreads:PTHREAD_SCOPE_SYSTEM user threads PTHREAD_SCOPE_PROCESS, pick one or the other not both)
• guard size
• stack address
• stack size(default minimum PTHREAD_STACK_SIZE set in pthread.h)

->void *(start_routine)-pointer to the function to be threaded.Function has a single argument:pointer to void.
->*arg-pointer to argument of function. To pass multiple arguments,sent a pointer to the structure.

Termination Of Thread

Function call: pthread_exit
void pthread_exit(void *retval);

Arguments

retval – return value of the thread.
This routine kills the thread.The pthread _exit never returns. If the thread is not detached the thread id and return value may be examined from another thread by using pthread_join.

Thread Synchronization

The thread libraries provide three synchronization mechanisms

• mutexes – Mutual exclusion lock: Block access to variable by other threads. This enforces exclusive access by thread to a variable or set of variables.
• joins–Make athread wait till others are complete(terminated).
• conditions variables- data type pthread_cond_t.

Benefits of Threads vs Processes

If implemented correctly then threads have some advantages of (multi) processes, They take:
• Less time to create a new thread than a process, because the newly created thread uses the current process address space.
• Less time to terminate a thread than a process.
• Less time to switch between two threads within the same process, partly because the newly created thread uses the current process address space.
• Less communication overheads -- communicating between the threads of one process is simple because the threads share everything: address space, in particular. So, data produced by one thread is immediately available to all the other threads.

POSIX Threads is a POSIX standard for threads. The standard defines an API for creating and manipulating threads.

Libraries implementing the POSIX Threads standard are often named Pthreads. Pthreads are most commonly used on POSIX systems such as Linux and Unix,

Algorithm

1. Start.
2. Provide function prototype and definition for the function that is used as thread.
3. Declare variables for storing the thread id and thread attributes.
4. Initialise the thread attributes.
5. Create the thread.
6. Call the thread for execution.
7. Wait for the thread to execute.
8. Stop.



Program

/*Program for the creation of simple thread created in a non detached manner.
* This program illustrates the manner in which a thread can be created from within the main() function.
* This program creates a thread called 'add' which accepts two integer values from the user and prints the sum of it.
* NOTE:->This program should be compiled using the command 'cc simplethread.c -lpthread' and executed using './a.out'.*/

//inculsion part

#include
#include
void* add(void*); //prototype of the thread function.
int main() //main function (return type should be int in linux).
{
int error; //variable to check error (optional)
pthread_t thread_id; //variable to store thread id.
pthread_attr_t thread_attribute; //variable to store properties of thread.
pthread_attr_init(&thread_attribute); //function call for setting the default properties.
error=pthread_create(&thread_id,&thread_attribute,add,NULL); //function for thread creation.

//error checking (optional)
if(error!=0)
{
printf("\nError in thread creation.\n");
exit(0);
}
error=pthread_join(thread_id,NULL); //function for thread calling.

//error checking (optional)
if(error!=0)
{ printf("\nError in thread joining.\n");
exit(0);
}
}
//function definition for the thread function.
void * add(void *args)
{ int a,b;
printf("\nEnter the first number.\n");
scanf("%d",&a);
printf("\nEnter the second number.\n");
scanf("%d",&b);
printf("\nThe sum is:\t%d\n",a+b);
}
Output

MULTIPLE THREAD

Algorithm


1. Start.
2. Provide function prototype and definition for the function that has to be used as thread.
3. Declare the variables for storing the thread id and thread attributes as required depending on the no: of threads to be created.
4. Initialize the thread attribute variables to their default values.
5. Set detach property of the thread.
6. Create the threads as required.
7. Wait for the thread to execute.
8. Stop.

Program

//Inculsion part.

#include
#include

//function prototype.
void * add(void *);

//Variable to count the executed thread.
int end;

//main function.
int main()
{
pthread_t tid1,tid2;
pthread_attr_t attribute;
pthread_attr_init(&attribute);

//function to set detach property of the thread.
pthread_attr_setdetachstate(&attribute,PTHREAD_CREATE_DETACHED);
pthread_create(&tid1,&attribute,add,(void *)1);
pthread_create(&tid2,&attribute,add,(void*)2);

//to wait for the thread to finish execution.
while(end<2)
{
}
}

//function prototype for the thread function.
void * add(void * args)
{
int a,b;
printf("\nEntered into %d thread\n",args);
printf("\nEnter the first number for thread %d\n",args);
scanf("%d",&a);
printf("\nEnter the second number for thread %d\n",args);
scanf("%d",&b);
printf("The sum computed by thread %d:\t%d\n",args,a+b);
end++;
}
output

DYNAMIC MULTITHREAD CREATION


Algorithm
1. Start.
2. Provide the function prototype and definition for the function that has to be used as thread.
3. Declare variables to store the thread id and thread attributes.
4. Accept the no. of threads from the user.
5. Create the threads by suitably initialising the thread variables.
6. Wait until the threads execute.
7. Stop.

Program

/*Program to describe dynamic multiple thread creation and passing arguments to it.
* This program illustrates the steps involved in creating multiple threads dynamically.
* This program accepts the number of threads from the user and creates it at run time.
* The procedure is similar to that we used to create multiple threads.

NOTE:->This module can be compiled using the command 'cc dynamic multithread creation.c -lpthread' and executed using './a.out'

//inculsion.
#include
#include
//function prototype.
void * thread_function(void *args[]);
//variable to know the end of threads execution.
int end;
int main()
{
int i,count,j;
int args[2];
pthread_attr_t attribute;
pthread_t tid;
pthread_attr_init(&attribute);
pthread_attr_setdetachstate(&attribute,PTHREAD_CREATE_DETACHED);

//for accepting the number of threads to be created.
printf("\nEnter the number of threads.\n");
scanf("%d",&count);
for(i=0,j=count;i
{

//inserting the arguments for the thread
args[0]=i+1;
args[1]=j;
printf("\n\t\tCreating thread %d.\n",i+1);
pthread_create(&tid,&attribute,(void *)thread_function,(void *)args);
printf("\n\t\tCreated thread %d\n",i+1);
sleep(1);
}

//waiting for the thread execution.
while(end!=count)
{
}
}

//function definition.
void * thread_function(void *args[])
{
int a,b;
a=(int)args[0];
b=(int)args[1];
printf("\n\t\tEntered into %d thread.\n",a);
printf("\nFirst value obtained from main function:\t%d\n",a);
printf("\nSecond value obtained from main function:\t%d\n",b);
end++;
}

Output

Thursday, June 11, 2009

How to take seminars effectively?

Posted by Sarjukottapuram

Seminar presentations are an integral part of most units, and they require skills that need to be learnt and rehearsed. Being able to give a good and clear presentation to a public audience is an asset you - and your future employer - will greatly value. Oral skills, alongside writing and research skills, teamwork, and time management, are aspects of your degree course, or key skills, which will have application to your future career in whatever field that may be. Future employers always ask for these key skills in references, and they are often seen as more important than the subject of your degree.

Design and delivery guidelines
The following points may be useful in designing and giving a seminar presentation:
• A seminar presentation is a means of communication with a specific audience (in the case of seminar presentations, with your fellow students). It is NOT a monologue, delivered to a lecturer, to prove to him/her that you’ve done your homework.
• A seminar presentation is an oral presentation. It is NOT a written essay that is simply read out from paper. If you don’t feel confident enough to speak completely freely, this would be ideal, and then use notes/bullet points on prompt cards. Make sure that your presentation uses English as it is spoken (so no longwinded sentences of the kind that you are likely to read), but also that the language fits the occasion (so: neither too formal, nor too casual).
• Speak in a lively and engaged way, so that you avoid monotonous delivery. If you give the impression that you are not particularly interested in your subject, no one else will be either (particularly if the session is early in the morning or late in the day). If in a large room, try to project your presentation, that is: speak loudly enough.
• Don’t speak too quickly, but keep your pace with your audience and allow your material to ‘sink in’.
• Make frequent eye contact with your fellow students. Address them as your audience - not just the lecturer.
• If at all possible, stand up while giving your presentation; if you prefer to sit down, try not to look down too much, or hide behind your notes. Choose a seat where you face your audience, rather than blend into it.
• At the beginning of your presentation, outline in a few words the aims of your presentation. When doing a joint presentation, the first speaker should explain how the different parts will work together. It is therefore absolutely essential that you co-ordinate your part of the presentation with your co-presenters in advance, so that you avoid overlaps, or an overall disjointed presentation.
• Distribute a prepared handout. This handout should give a run down of your presentation, preferably numbered or in bullet points and it should have a title. In any case it should be structured, and easy to read/follow. A handout is NOT identical with your notes, but a condensation of your presentation, so don’t have more than one to two A4 pages. Use illustrations only if they relate to your argument or if you refer to them.
• If you use (particularly lengthy) quotations from secondary sources, print them in full on your handout, as your audience will find it easier to follow them than if you just recite them. When you come to these quotes in your presentation, tell your audience they can find them on their handout.
• Also list on your handout all names and specific terms you mention in your presentation, particularly those that your audience may find difficult to note down without seeing them spelt out (i.e. foreign names, words, etc.).
Illustrating your argument
• A presentation is usually a timed exercise, and you must therefore select your material carefully so that it fits into the time allocated. Depending on your time, choose a selected number of key points, rather than attempt to cram everything you’ve read into your presentation. If there is too much, this will be likely to result in information overload for your audience.
• Concentrate on arguments or developments, rather than simple facts. The presentation should encourage your audience to think, and to follow this up with a discussion.
• To facilitate a subsequent discussion, you may want to end your presentation with a number of conclusions, or even better with a set of questions that emerge from your research. This is particularly important when you are dealing, for example, with theoretical arguments or texts, which you may not agree with, or which you don’t fully understand. Don’t try to gloss over this, but use it instead as a way into the discussion with your audience. For example:
 I don’t think I fully understand what X means when s/he argues... How did you interpret this...? What do you make of...?
•This will help clarify matters both for you and your fellow students who may indeed have similar problems.
• Aim to make your presentation more interesting by using visual aids, such as OHP transparencies. The most important thing about these is that they need to be tied in with your presentation:
• Visual aids are used to illustrate a point that you have made (or are about to make) in your presentation. Avoid using them as a kind of visual wallpaper, for example by ending your talk by showing a transparency without commenting on it.
• Choose transparencies to display items such as key points, graphs, grids, statistics, illustrations, and photos.
• If you use video clips, use them economically: don’t show about ten minutes when all you are talking about can be justified by a shorter extract. If you have a limited time for your presentation, use perhaps only one to three clips.
• Have your visual aids ready to use, and in the right order.
• Introduce visual aids and speak to them. For example, you could say: I am now going to show you... What I want to show you here is...
Preparing yourself for the presentation
• Before the presentation: make sure you are familiar with the room where you are giving your presentation, and with any audio-visual equipment you will be using. Make sure you are close to your equipment, and that you face the audience.
• It might be a good idea to rehearse your presentation at home. If possible, ask friends/house mates to listen to your performance, and ask them for advice which parts may still be a bit unclear.
• Time your presentation with a watch, to make sure you are within the limits you’ve been given.
• Do your last rehearsal at the latest the evening before the presentation. Have a good night’s sleep, avoid getting anxious, and don’t think about it until the moment of the presentation arrives. And do remember, your seminar tutor is always there in case you get stuck.

Seminars useful links
http://www.seminartopics.net/
http://www.bestneo.com/
http://www.freshersworld.com/resources/sp/mechsem.htm
http://www.seminartopics.in/
http://www.college-seminars.com/

Computer topics
http://www.seminartopic.org/seminars.php?catId=8&pageNumber=0
http://www.seminartopics.net/Seminars.php?flag=index&pageNumber=0&category=Computer%20Science
http://www.seminarsonly.com/computer%20science/computer%20seminar%20topics.php
http://www.computerseminartopics.net/

Electronics topics
http://www.seminartopic.org/seminars.php?catId=9&pageNumber=0
http://www.seminartopics.net/Seminars.php?flag=index&pageNumber=0&category=Electronic%20Science
http://www.seminarsonly.com/electronics/electronics%20seminar%20topics.php
http://www.electronicsseminartopics.com/

Civil topics
http://www.seminartopics.net/Seminars.php?flag=index&pageNumber=0&category=Civil%20Engineering


Electrical and Electronics topics
http://www.seminarsonly.com/nursing/Electrical%20&%20Electronics%20Seminar%20Topics.php

Mechanical topics
http://www.seminartopic.org/seminars.php?catId=15&pageNumber=0
http://www.seminartopics.net/Seminars.php?flag=index&pageNumber=0&category=Mechanical%20Engineering
http://www.seminarsonly.com/mech%20&%20auto/mechanical%20seminar%20topics.php