简体   繁体   English

使用-lpthread在C中进行多线程

[英]multithreading in C using -lpthread

So I designed a server to accept multiple clients in real time where the clients will 'speak' and the server will 'repeat' it. 因此,我设计了一个服务器来实时接受多个客户端,其中客户端将“讲话”,而服务器将“重复”它。 The clients will remain active constantly until I quit it. 在我退出之前,客户将一直保持活跃状态​​。 I tried implementing this using the -lpthread but the server will accept all the client connections, but then ignore all commands received except from the first client. 我尝试使用-lpthread实现此功能,但服务器将接受所有客户端连接,但随后会忽略从第一个客户端收到的所有命令。 Here is what I tried so far: 这是我到目前为止尝试过的:

int main(int argc, char *argv[]) {
    pthread_t client_thread;
    pthread_attr_t attr;
... 
while(1) {  /* main accept() loop */


    sin_size = sizeof(struct sockaddr_in);
    if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
    &sin_size)) == -1) {
        perror("accept");
        continue;
    }
    printf("server: got connection from %s\n", \
        inet_ntoa(their_addr.sin_addr));

    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for (int i = 0; i < MAX_CLIENTS; i++) {
        pthread_create(&client_thread, &attr, decider, new_fd);
        pthread_join(client_thread,NULL);
    }
...

Currently, the only options I can choose between are multithreading or thread pooling. 目前,我只能在多线程或线程池之间进行选择。 Thanks. 谢谢。

You call pthread_create and then immediately pthread_join . 您调用pthread_create ,然后立即调用pthread_join

The problem with that is that pthread_join will wait for the thread to exit, making your code serial instead of parallel. 这样做的问题是pthread_join等待线程退出,从而使您的代码变为串行而不是并行。

If you want to dynamically create a thread when you receive a connection, then create one thread. 如果要在接收连接时动态创建线程,请创建一个线程。 Don't create MAX_CLIENT threads in a loop, where all threads handle the very same connection. 不要在所有线程处理完全相同的连接的循环中创建MAX_CLIENT线程。


If you want to use a thread-pool, then create all threads first before the "main accept() loop", and simply have them do nothing (to begin with). 如果你想使用一个线程池,然后第一 “主接受()循环”之前创建的所有线程,并且简单地让它们什么也不做(以开始)。 Then use a (protected) queue where you add new connections, and the threads check this queue for new connections, and the one thread that doesn't already handle a connection will pick it up and process it. 然后使用(受保护的)队列在其中添加新的连接,线程检查该队列中的新连接,并且一个尚未处理连接的线程将对其进行处理。

In pseudo-code, something like this: 在伪代码中,如下所示:

thread_function()
{
    while (true)
    {
        sleep_while_queue_is_empty();
        get_descriptor_from_queue();

        handle_connection();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM