Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if more than one pthread uses a same function

I wonder what happens if two threads call the same function at the same time and the function is a UDP client that sends a text over the socket.

Considering the below code, I have been running it but I have not got any error yet. I wonder if it supposed to be crashed as the threads use the same source (function, variable, IP, port) at the same time, and how do they share the sources? I can imagine that the below code is a wrong usage of multi-threading, could you explain me how the threads should be used so that a thread would use the function only no other threads is using? In other word, how could it be thread-safe?

as an example C code on Linux:

void *thread1_fcn();
void *thread2_fcn();
void msg_send(char *message);

int main(void){
    pthread_t thread1, thread2;
    pthread_create( &thread1, NULL, thread1_fcn,  NULL);
    pthread_create( &thread2, NULL, thread2_fcn,  NULL);
    while(1){}
    return 0;
}

void *thread1_fcn(){
    while(1){
        msg_send("hello");
        usleep(500);
    }
    pthread_exit(NULL);
}

void *thread2_fcn(){
    while(1){
        msg_send("world");
        usleep(500);
    }
    pthread_exit(NULL);
}

void msg_send(char message[]){
       struct sockaddr_in si_other;
       int s=0;
       char SRV_IP[16] = "192.168.000.002";

        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        memset((char *) &si_other, 0, sizeof(si_other));
        si_other.sin_family = AF_INET;
        si_other.sin_port = htons(12346);
        si_other.sin_addr.s_addr = htonl(INADDR_ANY);
        inet_aton(SRV_IP, &si_other.sin_addr);
        sendto(s, message, 1000, 0, &si_other, sizeof(si_other));
        close(s);
}
like image 238
sven Avatar asked Jun 26 '13 21:06

sven


2 Answers

There isn't any problem with your code. Each thread, even if it runs the same code, has a separate stack, so a separate set of variables it works on. No variables are shared.

like image 118
ctn Avatar answered Oct 17 '22 16:10

ctn


Since you create and close the socket inside msg_send, nothing special will happen. Everything will work fine.

like image 42
Carl Norum Avatar answered Oct 17 '22 17:10

Carl Norum