如果多个pthread使用相同的函数会发生什么

sve*_*ven 5 c linux multithreading pthreads thread-safety

我想知道如果两个线程同时调用同一个函数会发生什么,并且该函数是一个通过套接字发送文本的UDP客户端.

考虑到下面的代码,我一直在运行它,但我还没有任何错误.我想知道它是否应该崩溃,因为线程同时使用相同的源(函数,变量,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);
}
Run Code Online (Sandbox Code Playgroud)

ctn*_*ctn 6

你的代码没有任何问题。每个线程,即使它运行相同的代码,也有一个单独的堆栈,因此它处理一组单独的变量。没有共享变量。


Car*_*rum 3

由于您在内部创建并关闭了套接字msg_send,因此不会发生任何特殊情况。一切都会很好。