【发布时间】:2022-09-25 08:14:38
【问题描述】:
我想同时处理从 MySQL 数据库中获取的数据。我将数据传递给每个线程进程(无需考虑线程安全;行在每个线程中独立处理):
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <pthread.h>
#include \"thpool.h\" // https://github.com/Pithikos/C-Thread-Pool
#define THREADS 10
struct fparam
{
int id;
char *data;
};
void process(void *arg)
{
struct fparam *args = arg;
// Processing ID and Data here
printf(\"%d - %s\\n\", args->id, args->data);
}
int main(int argc, char **argv)
{
threadpool thpool = thpool_init(THREADS);
// MySQL connection
MYSQL_RES *result = mysql_store_result(con);
int num_fields = mysql_num_fields(result);
struct fparam items[100]; // 100 is for the representation
MYSQL_ROW row;
int i = 0;
while ((row = mysql_fetch_row(result)))
{
items[i].id = atoi(row[0]);
items[i].data = row[1];
thpool_add_work(thpool, process, (void *)(&items[i]));
i++;
}
mysql_free_result(result);
mysql_close(con);
thpool_wait(thpool);
thpool_destroy(thpool);
exit(0);
}
当有很多行时,items 变得太大而无法放入内存(不仅仅是堆)。
如何限制存储在内存中的行数并在处理后删除它们?
我认为一个关键问题是我们不知道process 函数是否更快或从数据库中获取行。
-
“不仅仅是堆”是什么意思?你是说你不想使用堆?如果是这样,为什么不呢?
-
@kaylum 抱歉,我后来添加了它以避免在代码中不使用
malloc造成混淆。我对堆或堆栈都很好。 -
你是说数据行太多,连动态内存都太大了?在这种情况下,您需要在主线程和池线程之间进行同步,以便在池线程准备好接收它们时协调仅读取更多行。例如,使用计数信号量。
-
听起来您需要在结果集(可能是巨大的 #/rows)和线程池(有限的 #/worker 线程)之间实现一个队列。
-
如您所知,任何时候系统可能收到的数据多于它无法及时提供的服务,您应该考虑使用某种“队列”。以下是几个示例(您可以通过简单的 Google 搜索找到更多示例):log2base2.com/data-structures/queue/queue-data-structure.html、programiz.com/dsa/circular-queue 等等。您的工作线程读取下一个可用项目 (\"dequeue\") 并为其提供服务。即使“服务”可以并行发生,您的“出队”也可能需要一个锁。
标签: c