skmiley1
skmiley1

Reputation: 249

Concurrently sending packets

I am new to C, and want to understand how multithreading works with sockets.

I understand how to create threads, but I do not understand how they work in this context.

The two threads receive packets concurrently. When the first thread enters the receiveData function, and makes the recvmsg() call, will the second thread be blocked until the first thread receives the packet and exits the receiveData function?

Is there some way to prevent additional threads from being blocked?

void * tcp (void * arg){
    struct * info = arg;
    // set up socket fd
    fd = socket(AF_INET, SOCK_STREAM, 0);
    while(True){
        receiveData(info, fd);
    }
}

void * icmp (void * arg){
    struct * info = arg;
    // set up socket fd
    fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
    while(True){
        receiveData(info, fd);
    }
}

//function that is called by thread 1 and thread 2 concurrently
void receiveData(struct * info, int fd){
    int val = recv(fd, buf, 1000, 0);
}

Upvotes: 0

Views: 156

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126203

When you have two separate sockets like this, they are independent -- the first thread will block until data is available on its socket, and the second will block until data is available on its socket. If data arrives on one socket and not the other, then the thread blocked on the socket where data arrived will unblock (the recv will return) and loop until no more data is available. If data arrives on both sockets, then both threads will continue and loop.

Upvotes: 1

Related Questions