【问题标题】:Passing socket to thread instead of fd?将套接字传递给线程而不是 fd?
【发布时间】:2019-02-12 03:06:07
【问题描述】:

我正在使用这个函数来接受一个新的客户端并将它传递给一个线程

struct sockaddr_in client;
while(1) {
    len = sizeof(client);
    fd = accept(sock, (struct sockaddr*)&client, &len);
    if(fd>0) {
        CreateThread(NULL, 0, process_thread, (LPVOID)fd, 0, &thread);
        // pthread_create( &thread , NULL , process_thread , (int)fd);
    }
}

并像处理它

DWORD WINAPI process_thread(LPVOID lpParam) {
//void process_thread(int sock) {
    SOCKET fd = (SOCKET)lpParam;
    //int fd = sock;
    ....  
}

我也可以使用client 结构(sockaddr_in)创建一个新线程并在处理函数中选择 fd,例如

CreateThread(NULL, 0, process_thread, (SOCKET)client, 0, &thread);

以及如何?如果是这样,创建线程后如何接受?这可能吗?

谢谢

【问题讨论】:

  • client 不是套接字,所以我不知道“client 套接字”是什么意思。
  • 我已将问题编辑为struct sockaddr_in,抱歉

标签: c multithreading sockets


【解决方案1】:

你应该做的是创建一个新的结构来保存你的值:

struct process_thread_info
{
    struct sockaddr_in client;
    SOCKET fd;
};

然后你可以传递这个结构:

// We must use malloc to create a new struct for every client.
// We can't just declare one here and then use its address,
// because it might go out of scope before the process_thread receives the info.
struct process_thread_info *threadinfo = malloc(sizeof(struct process_thread_info));
threadinfo->fd = fd;
threadinfo->client = client;

CreateThread(NULL, 0, process_thread, threadinfo, 0, &thread);
// pthread_create( &thread , NULL , process_thread , threadinfo);

malloc 的任何其他用法一样,当线程free 使用完毕后,不要忘记将其作为结构。

【讨论】:

  • 结构体很棒,我已经知道了,但还没有考虑过,我可以将它传递给线程,非常感谢。
  • 抱歉,process_thread() 函数看起来如何?
  • @Rajana struct process_thread_info *info = (struct process_thread_info*)lpParam;
  • 而 lpParam(process_thread 的参数)是 process_thread_info 类型的?函数的返回类型是什么?
  • 也许没有大量代码的函数定义会很好。
猜你喜欢
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2016-09-03
  • 2021-09-15
  • 2019-09-04
  • 2021-12-14
  • 2013-12-25
  • 2019-07-04
相关资源
最近更新 更多