0
votes

I have a process ProcessA that starts 2 threads ThreadA and ThreadB. Both threads send and recv data from ProcessB using the same socket descriptor.

So essentially:

int s;

void thread_fnA(void*)
{
    while(1) {
        sendto(s);
        recvfrom(s);
    }
}

void thread_fnB(void*)
{
    while(1) {
        sendto(s);
        recvfrom(s);
    }
}

int main()
{
      s = socket(AF_UNIX, SOCK_DGRAM, 0);
      bind(s);
      dispatch_thread(A);
      dispatch_thread(B);

}

Is there a possibility that the message to be received by thread B could be received in thread A.

So sequence of events:

Thread A prepares a message and calls sendto();

Thread B starts executing and prepares a message and calls sendto();

Thread B calls recvfrom() simultaneously with Thread A.

However the message content expected by both threads are different. Can the messages be exchanged, ThreadB destined message be received by ThreadA.

Should the send and receive be involved in some locks. (Mutex)

2

2 Answers

1
votes

I would suggest another design, in where you have a single thread doing the sending and receiving, and message queues for the other threads.

When the send/receive thread receives a message it check what kind of message it is, and ad it to the (protected) queue of the correct processing thread. The processing threads (your current treads A and B) gets the messages from its respective message queue, and process the messages in any way it pleases. Then if thread A or B wants to send a message, it passes it to the send/receive thread using another queue, which the send/receive thread polls.

Alternatively, the processing threads (A and B in your example) could send directly over the socket. Or each have a different socket used only for sending.

0
votes

Since you are using the same socket in both threads it is possible that one thread reads the message that is destined to the other thread. Even if you use mutex, the design would be very difficult. You can open two sockets (or even pipes):

  • One socket is for communication in the direction A->B
  • The second socket in the direction B->A

A second possibility is having one socket with one writer (thread A) and one reader (thread B). The reader, when it receives a datagram, it decides, maybe based on datagram payload, what task to do. Or it can also send a task to other set of workers that will process the datagram.