Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 可重入或线程安全_Multithreading_Sockets - Fatal编程技术网

Multithreading 可重入或线程安全

Multithreading 可重入或线程安全,multithreading,sockets,Multithreading,Sockets,我已经为Hanlding多个客户端实现了这段代码。对此我有疑问。这个函数是重入函数吗 void *connection_handler(void *socket_desc) { //Get the socket descriptor int sock = *(int*)socket_desc; int read_size; char *message , client_message[2000]; //Send some messages to the

我已经为Hanlding多个客户端实现了这段代码。对此我有疑问。这个函数是重入函数吗

void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];

    //Send some messages to the client
    message = "Greetings! I am your connection handler\n";
    write(sock , message , strlen(message));

    message = "Now type something and i shall repeat what you type \n";
    write(sock , message , strlen(message));

    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , strlen(client_message));
    }

    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    //Free the socket pointer
    free(socket_desc);

    return 0;
}
如果它处理多个客户端,意味着它如何同步

我在main函数中使用pthread_create调用这个函数


谢谢。

我只能在这里看到未同步的
stdout
正在使用。我不明白。你能告诉我吗?你的问题是关于线程安全的。行
put(“客户端断开”);fflush(stdout);perror(“recv失败”)不是线程安全的,因为它们使用来自不同线程的相同输出流而不进行同步。所有其他代码都使用本地资源,因此是线程安全的。谢谢您提供的信息。但我想问的是连接处理程序函数。它是可重入的吗?我们可以关闭stdout并使用文件读/写来获得这些输出。使用
peror
并从多个线程写入同一输出流不是线程安全的。函数的其余部分是线程安全的。