我想知道如果两个线程同时调用同一个函数,而这个函数是以UDP客户端形式在套接字上发送文本,会发生什么。
考虑下面的代码,我已经运行了它,但是我还没有遇到任何错误。我想知道当线程同时使用相同的源(函数、变量、IP、端口)时,它是否应该崩溃,以及它们如何共享资源? 我可以想象出下面的代码是多线程的错误用法,请您解释一下如何使用线程,使得一个线程只使用函数,没有其他线程在使用。换句话说,如何实现线程安全?
以下是Linux上的C示例代码:
考虑下面的代码,我已经运行了它,但是我还没有遇到任何错误。我想知道当线程同时使用相同的源(函数、变量、IP、端口)时,它是否应该崩溃,以及它们如何共享资源? 我可以想象出下面的代码是多线程的错误用法,请您解释一下如何使用线程,使得一个线程只使用函数,没有其他线程在使用。换句话说,如何实现线程安全?
以下是Linux上的C示例代码:
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);
}
thread1_fcn()
和thread12_fcn()
应该仍然声明为接受void *
参数,以匹配pthread_create()
的期望。 - jxh