1
votes

I am creating an asynchronous chat application in C. I created two threads, one for receiving and another one for sending as follows.

void* send()
{
...
}

void* receive()
{
...
}

main()
{
..
inid = pthread_create(&incoming,NULL,receive,"Incoming thread");
outid= pthread_create(&outgoing,NULL,send,"Outgoing thread");

..

pthread_join(incoming,NULL);
pthread_join(outgoing,NULL);

..

}

What the problem is, the send and receive functions are called only once and the program terminates. I want both the threads to run forever till the user wishes to exit ( the condition to check for exit is defined in the send function). How to solve this?

1

1 Answers

3
votes

One solution is to have a while(input != exit) type of loop in send.

And make your main to only wait for outgoing thread (which means having pthread_join only for outgoing thread). So, when the user chooses to exit, the main will exit without waiting for the incoming thread.

Secondly, you need to use a blocking receive function in the receive function. So, it is either processing an incoming message or waiting for one.

Another solution is to have a while(input != exit) type of loop in main. Have a message queue defined in which main can queue messages to be sent and the outgoing thread consumes messages from this thread to actually send them.

The outgoing thread is either sending a message or is blocked until the queue has a message in it to be sent.

The input thread behaves in the same way as described in the previous solution.