c - 如何将多个参数传递给 c 中客户端服务器的线程?

标签 c multithreading sockets

我想创建一个并发服务器来处理多个客户端请求。所以我创建了一个线程函数来处理多个请求。我的问题是我有一个哈希表,它最初在服务器启动时加载了文件的内容,而且我也有套接字描述符和文件描述符。那么如何传递给线程函数。是否需要结构来存储参数并传递给线程?

我的代码是这样的:

struct UserData
{
    char *username; 
    char *password;

};

struct HashTable
 {
    int size;
    struct UserData *table
 };

int main()
{
 struct HashTable *htable;
  //socket sd to open socket in server
  and a Fd file descriptor to write to file
 // hash table loaded with contents and it is a structure
 /*create thread using pthread*/
 pthread_create(...,fun,..);

 }

 void * fun(void *arg)
 {
  .............
  }

我如何声明传递给线程函数的结构,包括套接字描述符 (sd)、文件描述符 (fd) 和哈希表指针等参数?当我写入文件 (fd) 时,我会使用互斥锁来锁定吗?

最佳答案

pthread_create()void * 作为它的最终参数,它被传递给你的线程入口函数,fun()案件。因此,您只需要定义一个结构,其中包含您要传递的所有字段:

struct ThreadArg {
    int sd; /* socket descriptor */
    int fd; /* file descriptor */
    struct HashTable *ht;
};

然后在您的 main() 中填写并传递给 pthread_create():

...
struct ThreadArg *arg = malloc(sizeof(struct ThreadArg)); /* you should check for NULL */
arg->sd = sd;
arg->fd = fd;
arg->ht = htable;
pthread_create(..., fun, (void *)arg);
...

然后在 fun() 中将其转换回去:

void *fun(void *arg) {
    struct ThreadArg *thArg = (struct ThreadArg *)arg;
    /* do whatever with thArg->sd, thArg->fd, etc. */
    ...
    /* free the memory when done */
    free(arg);
}

关于c - 如何将多个参数传递给 c 中客户端服务器的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103954/

相关文章:

c - 警告 - Expected ‘struct node **’ but argument is of type ‘struct node **’ 是什么意思?

c - C 中嵌套且可扩展的 for 循环

c - 当一个函数被另一个函数调用时,它的技术术语是什么?

java Fork/Join 池、ExecutorService 和 CountDownLatch

C++多线程成员变量

c - C 中的线程加工错误?

javascript - Node.js tcp 套接字关闭触发器

c - 这个表达式 1>0 在 C 中计算结果(在 64 位上)是什么?

c# - 概念: Using WCF Service VS.套接字VS。

java - 如何在 Java 中发送原始 SOAP 请求?