Tag Archives: C

Sorting strings and Overriding std::sort comparison

At that post, I try to illustrate one of the use case of comparison overriding for std::sort on top of a simple problem. Our problem is as follows:

Write a method to sort an array of strings so that all the anagrams are next to each other.

Continue reading Sorting strings and Overriding std::sort comparison

Share

Some possible Matrix Algebra libraries based on C/C++

I've gathered the following from online research so far:

I've used Armadillo a little bit, and found the interface to be intuitive enough, and it was easy to locate binary packages for Ubuntu (and I'm assuming other Linux distros). I haven't compiled it from source, but my hope is that it wouldn't be too difficult. It meets most of my design criteria, and uses dense linear algebra. It can call LAPACK or MKL routines.

I've heard good things about Eigen, but haven't used it. It claims to be fast, uses templating, and supports dense linear algebra. It doesn't have LAPACK or BLAS as a dependency, but appears to be able to do everything that LAPACK can do (plus some things LAPACK can't). A lot of projects use Eigen, Continue reading Some possible Matrix Algebra libraries based on C/C++

Share

Getting started to Thrust on source code...

Here I am sharing the code that I write while learning basics of the Thrust. It is self explanatory with its qualified comments.

You might just download the code here from my dropbox.

This code is crafted as I am learning THRUST Library and utilizing its great benefits with little effort on CUDA complexity. You might choose to download the code since I am so lazy to keep the code aligned below as it is pretty long. 🙁

Share

What is "long long" type in c++?

long long is not the same as long (although they can have the same size, e.g. in most 64-bit POSIX system). It is just guaranteed that a long long is at least as long as a long. In most platforms, a long long represents a 64-bit signed integer type.

You could use long long to store the 8-byte value safely in most conventional platforms, but it's better to use int64_t/int_least64_t from <stdint.h>/<cstdint> to clarify that you want an integer type having ≥64-bit.

Share

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

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