将套接字传递给线程而不是fd?

时间:2019-02-12 03:06:07

标签: c multithreading sockets

我正在使用此功能来接受新客户端并将其传递给线程

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);

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

谢谢

1 个答案:

答案 0 :(得分: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后使用线程for object in self.mapView.subviews{ if(object.theClassName == "GMSUISettingsPaddingView"){ for view in object.subviews{ if(view.theClassName == "GMSUISettingsView"){ for btn in view.subviews{ if(btn.theClassName == "GMSx_QTMButton"){ var frame = btn.frame frame.origin.y = frame.origin.y - 100 btn.frame = frame } } } } } } public extension NSObject { public var theClassName: String { return NSStringFromClass(type(of: self)) } }