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);
}
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.
Since you create and close the socket inside msg_send
, nothing special will happen. Everything will work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With