Random Number Generation in C

Here is the basic method to generating random number.


#include <time.h>
#include <stdlib.h>
srand(time(NULL));
int r = rand();

The different fact about this code is using time method to set the “seed” of the rand() function. Since the rand() function actually gives a pre defined sequence of  numbers and that sequence can be changed by setting different seed number by srand(). Thus we use the time value to have random numbers for different executions.

That’s all folks….

Share

File I/O in C

These are the basic operations to read and write a file in C;

1- Include the header files

#include <stdio.h>

2- Create a file object

FILE *fp;

3- Open file

fp = fopen("filename", "mode");

modes are ;
r = read
w = write (create file if does not exist)
a = append (create file if does not exist)
r+ = reading and writing
w+ = reading and writing. Deletes the content of the file beforehand
a+ = read and write. Append if the file exist.

4-write to file

fprintf(fp,"Testing n");

or

fprintf(fp,"Testing %dn", num);

5-read file

fscanf(input,"%d", &c); //c is any variable typed int

6-close file

fclose(fp);

Share

GDB for debug… (Multi-threaded program)

I am recently working on a project for my school assignment and I discover the help of the GDB debugger. (Little late but whatever…(at 3rd GRADE)) :).

I used it to discover problems of my multi-threaded code that uses also Semaphores. However, now I’ll talk about GDB debugger not semaphore or thread. Time to begin…

First of all, in linux you need to get the GDB packages. You can easily use the software center .

(IN TEMINAL)

Compile your source code as:
erogol@erogol-G50V:~<strong>gcc -g [source_name] -o[execution_file_name]</strong> (do not change the -g option deceleration since it can causes some silly errors).  Start GDB:  erogol@erogol-G50V:~ gdb
GNU gdb (GDB) 7.2-ubuntu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type “show copying”
and “show warranty” for details.
This GDB was configured as “i686-linux-gnu”.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.

(gdb) [all the commands will be written at that location]

NOTE:if you start it into the folder that includes your executable program you do not need to go to data path again in gdb, but you can go to the folder just like in the main terminal screen, using “cd”. If you are in the program folder then you can start gdb with the command “gdb [program_name]”

Open the program with gdb:

(gdb) file [program_name]

It will load the program.

Then: use the command as needed.

run – run the program

break [‘line_no’ or ‘code on the line’] – put a breakpoint to the program. “breakpoint” is the place that you code will be stopped when you run it.

step – go step by step by pressing “ENTER” of the program after it stops on one of the break point.

help all – get the all commands and explanations.

(When program creates new thread gdb will warn you)

info threads – shows threads number and some additional info.

thread [thread_no] – switch the watching thread.

info locals – show all the local variables and the values.

thread apply all info locals – show all the local values of all the threads.

print [variable_name] – show the value of the variable

finish – it finishes the function execution of the current one.

continue – exit from the step mode and continue the execution.

Also when you press CTRL+C in the execution time, program will be paused not canceled.

These are the basic commands that are used for my project debug, for more info here is a good tutorial:

http://www.haifux.org/lectures/211/gdb_-_customize_it.html

Share


Using Semaphore in C coding (Posix)

Semaphore is used for dealing with the synchronisation problem between processes and threads. It is well defined library structure that comes with the POSIX libraries.

Here a example that have a thread synchronisation problem between two threads. Here is the code.


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define UPTO 10000000
int count = 0;
void * ThreadAdd(void * a)
{
int i, tmp;
for(i = 0; i < UPTO; i++)
{
sem_wait(&mutex);
tmp = count;      /* copy the global count locally */
tmp = tmp+1;      /* increment the local copy */
count = tmp;      /* store the local value into the global count */
//printf("The count is %d in %dn", count, (int)pthread_self());
sem_post(&mutex);
}
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, ThreadAdd, NULL))
{
printf("n ERROR creating thread 1");
exit(1);
}
if(pthread_create(&tid2, NULL, ThreadAdd, NULL))
{
printf("n ERROR creating thread 2");
exit(1);
}
if(pthread_join(tid1, NULL))    /* wait for the thread 1 to finish */
{
printf("n ERROR joining thread");
exit(1);
}
if(pthread_join(tid2, NULL))        /* wait for the thread 2 to finish */
{
printf("n ERROR joining thread");
exit(1);
}
if (count < 2 * UPTO)
printf("n BOOM! count is [%d], should be %dn", count, 2*UPTO);
else
printf("n OK! count is [%d]n", count);
pthread_exit(NULL);
}

This code will have the synchronisation problem when you use it since the shared variable count will be updated with two threads unexpectedly. Consider the “for” section of the function “ThreadAdd”. In that section count variable is updated but this increment and update action is not atomic operation (that means, it needs multiple system calls in low level) so in the middle of the for loop the other thread can get the control and continue its execution. As a result it causes unexpected result. Let’s analysis execution flow of the threads.

initially “count = 1”

Thread 1:
tmp = count;
tmp = tmp+1
Thread2
Thread2
Thread2
count = tmp //(count = 2)

Thread 2:
Thread1
Thread1
tmp = count;
tmp = tmp+1
count = tmp  //(count = 2)  Two for loops the give same result for count. So result is 2 instead of 3

For this kind of problems we can easily use Semaphore. Here the basic functions:

sem_t sem_name; //create variable

sem_init(&sem_name, Flag, Init_val) // initialise the semaphore var. “Flag” decides whether it is shared by processes. “Init_val” is the initial value of the semaphore.

sem_wait(&sem_name);//waits while semaphore value will  be positive, if value is positive it makes the semaphore negative again to make he other processes waiting.

sem_post(&sem_name);//increment the semaphore value, so one of the waiting thread can continue its operations.

sem_destroy(&sem_name);

Here the solution of the above code with semaphore:

;
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#define UPTO 10000000
int count = 0;
sem_t mutex;
void * ThreadAdd(void * a)
{
int i, tmp;
for(i = 0; i < UPTO; i++)
{
sem_wait(&mutex);
tmp = count;      /* copy the global count locally */
tmp = tmp+1;      /* increment the local copy */
count = tmp;      /* store the local value into the global count */
//printf("The count is %d in %dn", count, (int)pthread_self());
sem_post(&mutex);
}
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2;
sem_init(&mutex, 0, 1);
if(pthread_create(&tid1, NULL, ThreadAdd, NULL))
{
printf("n ERROR creating thread 1");
exit(1);
}
if(pthread_create(&tid2, NULL, ThreadAdd, NULL))
{
printf("n ERROR creating thread 2");
exit(1);
}
if(pthread_join(tid1, NULL))    /* wait for the thread 1 to finish */
{
printf("n ERROR joining thread");
exit(1);
}
if(pthread_join(tid2, NULL))        /* wait for the thread 2 to finish */
{
printf("n ERROR joining thread");
exit(1);
}
if (count < 2 * UPTO)
printf("n BOOM! count is [%d], should be %dn", count, 2*UPTO);
else
printf("n OK! count is [%d]n", count);
sem_destroy(&mutex);
pthread_exit(NULL);
}

Share