|
#include
#include
#include
#include
struct message_queue_t
{
size_t MaxMessageSize;
unsigned int Maxmessages;
char *MessageBuffer;
pthread_mutex_t lock;
int rear,front;
pthread_cond_t notempty;
pthread_cond_t notfull;
}
struct message_queue_t *queue;
message_queue_t *message_create_queue(size_t MaxMessagesize,unsigned int MaxMessages)
{
pthread_mutex_init(&queue_lock,NULL);
pthread_cond_init(&queue->notempty,NULL);
pthread_cond_init(&queue->notfull,NULL);
queue->rear=queue->front=0;
queue->MaxMessageSize=MaxMessageSize;
queue->Maxmessages=MaxMessages;
struct message_queue_t Buffer[10];
queue=Buffer;
}
void *message_claim(message_queue_t *queue,void *message)
{
pthread_mutex_lock(&queue->lock);
while((queue->rear+1)%MaxMessages==queue->front)
{
printf("wait for not full \n");
pthread_cond_wait(&queue->notfull,&queue->lock);
}
strcpy(queue->[rear]->MessageBuffer,message);
queue->rear++;
if(queue->rear>=queue->MaxMessages) queue->rear=0;
pthread_cond_signal(&queue->lock);
}
void message_send(message_queue_t *queue,void *message)
{
char str;
while(1)
{
scanf("send :%s \n",str);
message_claim(queue,str);
sleep(1)
}
printf("xend stopped ! \n");
return NULL;
}
void *message_receive(message_queue_t *queue)
{
char *str;
pthread_mutex_lock(&queue->lock);
while(queue->rear==queue->front)
{
printf("wait for not empty \n");
pthread_cond_wait(&q->notempty,&queue->lock);
}
strcpy(str,queue->[front]->MessageBuffer);queue->front++;
if(queue->front>=maxMessages) q->front=0;
pthread_cond_signal(&queue->notfull);
return str;
}
#define OVER -1;
void *message_release(message_queue_t *queue)
{
char *str;
while(1)
{
str=receive(&queue);
if(queue==OVER) break;
printf("%s->receive \n",str);
sleep(2);
}
printf("release,stopped ! \n");
return NULL;
}
void message_delete_queue( message_queue_t* MessageQueue )
{
if (!MessageQueue)
return;
if (MessageQueue)
free(MessageQueue->MessageBuffer);
free(MessageQueue);
}
int main( void )
{
pthread_r th_a,th_b;
boid *retval;
message_create_queue(10,10);
pthread_create(&th_a,NULL,message_send,0);
pthread_create(&th_b,NULL,message_receive,0);
pthread_join(th_a,&retval);
pthread_join(th_b,&retval);
return 0;
}
|
|