Condition variable is a mechanism to implement producer/consumer idiom.

Producer will put data/job into a queue.
Consumer will deque the queue and work on that data.

Usually you should have one producer thread and multiple consumer threads.
In your case one data preparation thread and multiple data processing threads.

I haven't worked much on boost but looks like you haven't implement the data_prepartaion_thread right.

Because this logic [ICODE] while(int_vector.size() != 10)[/ICODE] shouldn't full fill unless all of your consumer threads are busy and your queue is over flown (which still can happened on the busy server, but i have a feeling that wasn't your intention, i think you wanted to enter 10 jobs)

[QUOTE]The condition variable would only awake the data_processing_thread if and only if the condition_variable is waiting for the signal already
[/QUOTE]
That means if none of the data processing threads were on the conditional wait, then signal might get loss.

But its very easy to fix. because your data_processing_thread shouldn't sleep/wait on condition variable if there is already data/job available to process.

So before it goes to sleep, it should check if there is any data available in the queue. If there is data, then no point of sleeping, lets process those. if there is no data, then lets sleep, and Producer_thread/data_preparation thread will signal/broadcast when data is available.

Two advantage of this: 1) It fixes your problem
2)condition variable is expensive (if you are thinking in billions of jobs), it uses mutex( and mutex uses futex ...

Suggestions made by vijayan121 is very good and I would have made the same suggestions.
But dont worry about small object allocation if you are only started to learn thread and concurrency.

First I would suggest to read about threads and different kind of locks and also lock free algorithms.

Here is an example of lock free algorithm which will use L1 and L2 cache, will try to avoid false sharing.

Lets say you have quad core pentium i5/i7 machine and you want to sort 100 million integers. your L1 cache size is 256 byte. and L2 cache size is 1 MB (cache size differs from machine to machine, you can use getconf on linux to find the cache size.)

So a quad core on i5/i7 will have two hardware thread per core which will share L1 instruction cache and data cache.

Anyway, you want to create 4*2 (hardware thread ) = 8 thread at least to sort your 100 million integers.

You will use very simple data structure, vector (as it access row mejor order and contiguous memory ) and will use very simple sorting algorithm, merge sort.

Merge sort uses the basic divide and conquer mechanism which we will use to divide the load as well.

So you want to divide your full data set into 8 parts as you will have 8 threads.
When you hit L2 cache size, 1 MB of data, you might not want to divide any more. You certainly wont divide less than ...

Just food for thought:
Performance of network programming mainly depends on how you are processing your datas.
How you are sharing the data among several component of your software?
How you are sharing the data among several processes on the machine? (shared memory/pipe/file fifo, mapped memory)
How you have distributed load and data among the cores? use of data structure. use of L1,L2,L3 caches.
Threads and locking: what is spin lock, what is mutex, read/write lock, semaphore, condition variables? thread specific data?
Locality matters! what does that mean?
small object allocation.
dont do premature optimization.
what is lock free algorithm?
what is wait free algorithm?
How can we use atomic operations?

I thought I will explain those questions, but each of those will be big article, so just a guideline for further reading.

Looks like its all about function pointer.
But I think your code has little bit definition issue?
If I am right it should be like this:

[CODE]
typedef void ( set_malloc_handler)( void(f)() ) ;
//Which means set_malloc_handler is a function pointer, which takes another function pointer as argument.
[/CODE]

Here is an example below:

[CODE]

include <iostream>

typedef void ( set_malloc_handler)( void(f)() ) ;

void firstFun( void(*f)() ){
f();
}

void callme(){
std::cout << "Call me" << std::endl;
}
int main() {
set_malloc_handler myfun = firstFun; //myfun is a function poitner vairbale of type set_malloc_handler, and its value is firstFun
myfun(callme);
}

[/CODE]

Output of this function is:
Call me

I am not sure why people downvote others when someone tries to help.
Anyway.. here is a solution for your problem.

[URL="

if it can solve your problem in 6 seconds then of course its a good solution, isn't it?
If it cant then its not a good solution. So you can give it a try.

if the upper limit of your two number is 2 ^ 32 which is 4294967296 and sqrt of this 65536.

so 65536 is 5 digit number, for a 100,000 there are only 9592 prime numbers according to this site [URL="

is there any upper limit of i/j and any memory limit?

@vijayan121 Cool..

Little optimization if there are millions of keys and million of values per keys.

[CODE]

template< typename K, typename T, typename C, typename A >
typename std::multimap<K,T,C,A>::size_type num_unique_keys( const std::multimap<K,T,C,A>& mmap )
{
if( mmap.size() < 2U ) return mmap.size() ;

const C& cmp = mmap.key_comp() ;
typename std::multimap<K,T,C,A>::size_type n = 0 ;
auto prev = mmap.begin()->first ;

for( auto iter = mmap.begin() ; iter != mmap.end() ; iter = mmap.upper_bound( iter->first )  )
    ++n;

return n ;

}
[/CODE]

EDIT:
Just little bit cleaner version:
[CODE]
template< typename T>
typename T::size_type num_unique_keys( const T& mmap )
{
if( mmap.size() < 2U ) return mmap.size() ;

typename T::size_type n = 0 ;

for( auto iter = mmap.begin() ; iter != mmap.end() ; iter = mmap.upper_bound( iter->first )  )
    ++n;

return n ;

}
[/CODE]

[QUOTE]ps: thx mike, i didn't know auto could be used this way, i thought that keyword is useless [/QUOTE]
That is [URL="

[QUOTE]Barring an off-by-one error in your array indexing, it works fine on my end.[/QUOTE]
Narue is correct. It works fine at my side as well.

Try for sit D and row 8, it is somewhere in the middle. at least you should see X
Then fix your array indexing.

Hi,

Your entire program is almost correct.

Only problem is you are resetting your cinemas in display function:
[CODE]
// This is in your display function. so just before display its resetting your entire array.
for( int row = 0; row < 17; ++row )
for( int column = 0; column < 20; ++column )
{
cinema[row][column] = '*';
}
[/CODE]

Remove that code and take it to the main, you need to set cinemas to "*" only once.

so your main should look like this:

[CODE]
int main ()
{

char choice;
bool done = false;
char cinemas[17][20];

for( int row = 0; row < 17; ++row )
    for( int column = 0; column < 20; ++column )
    {
        cinemas[row][column] = '*'; //NOTICE spelling of cinemas, in your display its cinema, as that is the name of your parameter, but in main its cinemas.
    }

    //Rest of the code.

}
[/CODE]

Hi,

Inheritance with virtual functions and virtual inheritance are two different things. After reading your initial question, I think you first need to read about normal inheritance with virtual functions.

Virtual functions are for implementing polymorphism.
If a class is derived from another class and when you create a object of the derived class, contiguous memory is allocated for the entire object: memory needed for base class + derived class.

See the following example:

[CODE]

class A{
int a;
virtual int getInt(){ return a;}
};

class B : A{
int b;
virtual int getInt(){ return b;}
};

B objectB; // size of objectB will be 16, 4 for int a from class A and 4 from int b from class B and 8 byte for virtual function.
[/CODE]

Notice only one pointer (8 byte) allocated for virtual function getInt() in vtable. Not two pointers for getInt() in A and getInt() in B.

I hope you know how virtual functions work, so i am not giving any example of how to use getInt(), but if you dont know, let me know.
for further reading, see below:
[URL="

mike_2000_17 commented: pretty good! +14

Hi,

I was just trying to show how type specific methods can be passed to generic codes in C.

[QUOTE]Using the "method" approach of storing pointers to functions in the object itself is a pointless waste of memory as the cost of each object doesn't justify the obj->method() syntax since you don't get the benefit of an implicit this argument as you would in C++.[/QUOTE]

I beg to differ on this one, I agree that we need to pass the obj to every method calls, but when ever you want to write a server which will load dynamically loaded modules, you need this approach. As server has to be generic as much as possible.

I have seen fair amount of server side open source in my relatively short career ( :) ), and each of them use this approach to load modules on basis of the C++ object like struct.

[QUOTE]While making C more like C++ is an enlightening exercise, you'd do well to consider that C doesn't make a good C++. If you want C++, use C++. Otherwise, use C properly instead of trying to turn it into an ugly and difficult to use C++.[/QUOTE]
I 100% agree on this and thats why I don't code on C any more. :)

Hi,

Narue's example doesn't have polymorphic/virtual methods.
If you want to develop any robust C project, you need to use struct in such a way that you can write generic codes.

Here is an example using the vector(as we are talking about vector)
I wrote it hurriedly and haven't been writing any C code for a long time, so it can be improved a lot. But I hope it conveys the basic example of how to use C to develop polymorphic and generic object.

In C you can do this using function pointer.
I have written a vector struct which also holds the relative function pointers.

First lets have a look at the main

[CODE]
/main.c/

include "vector.h"

void GenericDisplay(vector *v){
v->display(v);
}

void GenericFree(vector *v){
free((
v)->data);
free(v);
v = NULL;
}

int main(void) {

vector *intV = createIntgerVector(10);
int i;

for(i = 0; i < 10; i++){
    *(int *)(intV->at(intV,i)) = i; /*Initialization, I know it looks dirty. improve it :)*/
}

vector *doubleV = createDoubleVector(10);
for(i = 0; i < 10; i++){
    *(double *)(doubleV->at(doubleV,i)) = i; /*Initialization, I know it looks dirty. improve it :)*/
}

GenericDisplay(intV);
GenericDisplay(doubleV);

GenericFree(&intV);
GenericFree(&doubleV);

return EXIT_SUCCESS;

}

[/CODE]

It will print:

Int vector
0 1 2 3 4 5 6 7 8 9
Double vector
0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00

Now lets have a look at the vector.h

[CODE]
/vector.h/

include <stdio.h>

include <stdlib.h>

struct _vector;
typedef struct _vector vector;
typedef void (vector_method)(vector v);
typedef void
(vector_method_value)(vector v,int ...

Did it help? I got a feeling that you didnt get me. Let me know if I wasn't clear enough. I made couple of changes on the last post's code.

if vector not allowed then use array!!

[ICODE]bool alreadyShuffled[SUIT_SIZE * RANK_SIZE];[/ICODE]
initialize it with false;

Last post i checked it for index, but if you want to do it for cards, then change the logic for cards.
and if you want to do it exactly 52 times, then you need to decrement your i just before continue;

Here is a suggestion how you can implement it. I notice that you don't have a card Identifier in your Card class, so I added one and used this to check if this card has already shuffeled. Change your code whatever way you like.

[CODE]
class Card{
int cardIdentifier; //create it from 0 - 51 or 1-52, give each card an unique identifier.
......
int getCardIdentifier(){return cardIdentifier;}
};
[/CODE]

[CODE]
void Deck::shuffle()
{
int max = SUIT_SIZE RANK_SIZE;
bool alreadyShuffled[SUIT_SIZE
RANK_SIZE]; //initialize it with false.

for(int i=0; i<max; i++)
{
    int randNum = rand() % 52;

   if(alreadyShuffled[cardDeck[randNum].getCardIdentifier()] == false){
         i--; // bad idea as it will shuffle all the cards. dont use it
         continue;
   }
    alreadyShuffled[cardDeck[randNum].getCardIdentifier()] = true;
    swap(cardDeck[i],cardDeck[randNum]);
    cout<<cardDeck[i]<<"   ";

}
[/CODE]

Hi,

What do you mean by repeated cards. I just skimmed through the code and looks like it may shuffle same card multiple times, but it shouldn't create any duplicate card.

Your shuffling algorithm is based on rand(), and if modular is too small then you might get same index multiple times.

If you don't want to shuffle same index twice, you can simply use a bool vector to check if that index has already been shuffled.

But your code is also good, as in real life game you may shuffle same index/position couple of times.

[CODE]
void Deck::shuffle()
{
int max = SUIT_SIZE * RANK_SIZE;
std::vector<bool> alreadyShuffled(max); // it will create a vector of max size, and all index will be initialized as false.
for(int i=0; i<max; i++)
{
int randNum = rand() % 52;
if(alreadyShuffled[randNum])
continue;
alreadyShuffled[randNum] = true;
swap(cardDeck[i],cardDeck[randNum]);
cout<<cardDeck[i]<<" ";
}
}

[/CODE]

Hi,

Here is another way of static polymorphism.
[URL="

Hi,

I was thinking of writing this post as a reply of [URL="

m4ster_r0shi commented: Cool. Now, I'd like to see an example with the parametric base class pattern (PBCP). (CRTP is also known as the parametric subclass pattern (PSCP)) +7
mike_2000_17 commented: Nice! I rarely use CRTP, might do so in the future! +14

Here is a compile time Polymorphism example for JAVA using the above classes.

EDIT: ITS SHOWING C++ CODE, BUT THESE ARE ACTUALLY JAVA CODE.

[CODE]
package com.generic.myanimal;

public interface GenericAnimal {

public void makeAnimalCry();

}
[/CODE]

[CODE]
package com.generic.myanimal;

public class Dog implements GenericAnimal {

@Override
public void makeAnimalCry() {
    // TODO Auto-generated method stub
    System.out.print("Woof Woof!!");
}

}
[/CODE]

[CODE]
package com.generic.myanimal;

public class Cat implements GenericAnimal {

@Override
public void makeAnimalCry() {
    // TODO Auto-generated method stub
    System.out.print("Miaou..");
}

}
[/CODE]

[CODE]

public class Animal <T extends GenericAnimal>{

public void makeAnimalCry(T animal){
        animal.makeAnimalCry();
}
/**
 * @param args
 */
public static void main(String[] args) {
    Dog dog = new Dog();
    Cat cat = new Cat();

    Animal<Dog> animal1 = new Animal<Dog>();
    animal1.makeAnimalCry(dog);

    Animal<Cat> animal2 = new Animal<Cat>();
    animal2.makeAnimalCry(cat);

}

}
[/CODE]

I am not expert of java, so cant give expert opinion, or I should say will give more biased opinion towards c++.

But polymorphism in C++ is way too powerful than Java. I am off to home now. Will try to write an example why C++ is more powerful.

Please try to make some effort to do your OWN homework!!!!
Here several programmers can solve it without even blink of an eye, BUT I am pretty sure no one will take this bait to solve your school homework.

Hi,

You havent mentioned what error you are getting.
But I am assuming that isFull() is there and you will be able to fix the normal errors like [ICODE]using namespacestd;[/ICODE] should be acutlaly [ICODE]using namespace std; [/ICODE] and [ICODE]top[/ICODE] and [ICODE]elements[/ICODE] need to be declared.

Still you gonna face linker issues.
You can solve liker issues in several ways:

FIRST WAY) Keep everything in header. This is the most preferred way. Here is a working code where I have removed cpp file and moved the non inline member function to header file. Most easiest way to get rid of linker issues. But may create huge executables. But for your purpose (student/homework), I would suggest that you always include your member functions in the header file.

[CODE]

ifndef STACK_H

define STACK_H

include<iostream>

using namespace std;

template<class stackElem, int maxSize=80>
class stack
{
int top;
stackElem elements[maxSize];

public:
stack()
{
top=-1;
}

bool push(const stackElem &item);
bool isfull(){return top == maxSize;}

};

//#include "stack.cpp"

template<class stackElem, int maxSize>
bool stack<stackElem,maxSize>::push(const stackElem &item)
{
if(isfull())
return false;
elements[top]=item;
top++;
return true;
}

endif / STACKH /

[/CODE]

SECOND WAY: If you want to put your member functions in cpp file anyway, still you can do it like below:

[CODE]
//stack.hpp

include<iostream>

using namespace std;

template<class stackElem, int maxSize=80>
class stack
{
int top;
stackElem elements[maxSize];

public:
stack()
{
top=-1;
}

bool push(const stackElem &item);
bool isfull(){return top == maxSize;}

};
[/CODE]

[CODE]
//stack.cpp file.

include "stack.h"

using namespace std;

template<class stackElem, int maxSize> ...

Hi,

You need to setup your ethernet card in promiscuous mode, in linux you can use the commands to see every packet.

ifconfig eth0 promisc - Put nic into promiscuous mode to sniff traffic.
tcpdump -n host not XXX.XXX.XXX.XXX | more - Sniff net but ignore IP which is your remote session.
ifconfig eth0 -promisc - Pull nic out of promiscuous mode.

tcpdump uses [URL="

Hi,

Dont worry about subset. First try to do permutation for a word.
If you can generate permutation of a word, then subset is really easy.
You can treat each substring as a word and generate permutation for that word, you can use std::set to get rid of duplicates.

So, again, try to generate permutation for a single word!!. Do you need to help to generate permutation for a single word?

When you read almost every reply of this thread and try to match which one you are..

skilly commented: 1 bad apple... +0

Ahhh.. right.. still i sometime write my turbo C days coding style which I did 10 years ago!! sometime childhood habits doesn't go away. :)

Hi,

You can not return a local array. returning a local array will create invalid memory access. Your [ICODE]double f_g [2];[/ICODE] is a local array and as soon as you are getting out of the function, your address is invalid.

So [CODE] cout << "asd: " << asd[0] << ", " << asd[1] << endl; //This will access the invalid memory and potential crash will happened[/CODE]

  • is the notation of pointer.
    A pointer variable is a variable which holds a address of a variable.

[CODE]
int x = 10; //x is a integer vairable which holds 10
int *i = &x; // i is a pointer type varirable which holds the address of x.

cout << i; //will print the address of x
cout << *i // will print 10. we are access x indirectly through i.

*i = 5; //This will set x value as 5.
cout << x; //this will print 5 as we have changed its value.

[/CODE]

Now about Array:
You can think of an array as a pointer which points to a consecutive set of bytes.
[CODE]
int array[10];// this allocates 10 integers and array name binds to the first integer address.
[/CODE]

Now, you dont want to return an array. actually you dont need to.

[CODE]

void function(int result[2]){
result[0] = 5; // this will change the original array as result is bind to the address of that array.
result[1] = 6;
}

void main(void)
{
int arr[2];

function(arr); //passes the address of ...

Mike_2000_17 and Narue
Just a thought:
You should write a beginner's tutorial on C++0x for Daniweb. That will be a great way to promote this site. I can also contribute on some easier topics!!.

sergent commented: good idea! +4

iostream would be definitely tough one to start with.
I would suggest to see some easier(!) one first.
Like list, string, vector. I think if you can understand these three, would cover lots of basic and advanced c++ concepts.
Then the Algorithms.
Best of luck. :)