Im working on a client (that use a GUI and a socket). The GUI (running on the main thread) create on the fly commands of my protocol, every time I create a new command I append it in a dynamic stack.
In another thread (using pthread), I check if there is a command in the stack then send it progressively using a socket (which is non-block btw). When the command on the top of the stack is done sending I pop the stack (which means that the command is removed and each commands below the first element are pushed up).
Now as you might guess I have huge problems to synchronize that… I try to use some flags, mutex but I always end up with some access violation on the memory.
Basically what Im doing is this:
In the main thread when (ie) the user press a button:
char cmd[ 50 ] = "My new protocol command";
AppendCommandToSendStack( cmd );
In another thread:
if( SendStackCount )
{
SendCommand( 0 ); // 0 = The top of the stack.
if( IsCommandDoneSending( 0 ) )
{
RemoveCommandFromStack( 0 );
}
}
Can anybody help me or give me some pointers on how to make this mechanism work. Or another approach that would result in the same or similar workflow as Im trying to implement.
Tks in advance!
[ Update ]
I start reading on semaphore and it seems thats exactly what I need… however it doesn’t seems to work… this is what Im doing in pseudo code:
sem_t mutex;
int stack_count;
command *stack;
main()
{
// Init & Connect client.
// Start Thread
sem_init( &lock_stack, 0, 1 );
while( 1 )
{
sem_wait( &lock_stack );
++stack_count;
stack = ( command * ) realloc( stack, stack_count * sizeof( command ) );
strcpy( stack[ stack_count - 1 ].cmd, "new command" );
sem_post( &lock_stack );
}
}
thread()
{
while( 1 )
{
sem_wait( &lock_stack );
if( stack_count )
{
// Send stack[ 0 ].cmd via socket then when done pop the stack like this:
--stack_count;
if( 0 < stack_count )
{
memcpy( &stack[ 0 ],
&stack[ 1 ],
( stack_count - 1 ) * sizeof( command ) );
}
}
sem_post( &lock_stack );
}
}
Since Im basically new to this am I missing something obvious, because I still have memory access violation that “seems” to happen randomly on the stack array.
You have a classic example of producer-consumer problem. You want to
producecommands, while other threadsconsumethem. You can have a look at http://en.wikipedia.org/wiki/Producer-consumer_problem which explains how to implement a basic producer-consumer problem.