[英]Out of memory in a thread pool in C, Linux
我需要创建无限循环,并使用线程池创建例如200个线程来完成无限循环的工作。
我正在使用此线程池-https: //github.com/Pithikos/C-Thread-Pool
同时,我正在监视服务器资源(使用htop),并发现内存以每秒3 MB的速度增长,直到内核杀死应用程序为止。
编码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "thpool.h"
#define MAX_IPv4 256
/* Args for thread start function */
typedef struct {
int octet1;
int octet2;
int octet3;
int octet4;
} args_struct;
/* Thread task */
void task1(void *args) {
args_struct *actual_args = args;
printf("%d.%d.%d.%d\n", actual_args->octet1, actual_args->octet2, actual_args->octet3, actual_args->octet4);
/* Do some job */
sleep(1);
/* Free the args */
free(args);
}
/* Main function */
int main( void ) {
int i=0, j=0, n=0, m=0;
/* Making threadpool n threads */
threadpool thpool = thpool_init(200);
/* Infinite loop start from the certain ip*/
while (1) {
for (i=0; i < MAX_IPv4; ++i) {
for (j=0; j < MAX_IPv4; ++j) {
for (n=0; n < MAX_IPv4; ++n) {
for (m=0; m < MAX_IPv4; ++m) {
/* Heap memory for the args different for the every thread */
args_struct *args = malloc(sizeof *args);
args->octet1 = i;
args->octet2 = j;
args->octet3 = n;
args->octet4 = m;
/* Create thread */
thpool_add_work(thpool, (void*)task1, (void*)args);
}
}
}
}
/* Start from 0.0.0.0 */
i=0;
j=0;
n=0;
m=0;
}
/* Wait until the all threads are done */
thpool_wait(thpool);
/* Destroy the threadpool */
thpool_destroy(thpool);
return 0;
}
如何解决这个问题?
看着你的库(尤其是问题, 这一个大约内存消耗)。
建议检查作业队列长度threadpool.jobqueue.len
;
在将作业添加到队列后,也许您的代码可以检查
不幸的是, threadpool
是一个不透明的指针,您不能直接访问该值。
我建议在thpool.c
为thpool.c
添加一个函数:
int thpool_jobqueue_length(thpool_* thpool_p) {
return thpool->jobqueue->len;
}
并且不要忘记thpool.h
的声明
int thpool_jobqueue_length(threadpool);
然后修改您的代码
const int SOME_ARBITRARY_VALUE = 400
...
thpool_add_work(thpool, (void*)task1, (void*)args);
while( ( thpool_jobqueue_length(thpool) > SOME_ARBITRARY_VALUE ) ) {
sleep(1);
}
...
查看thpool_add_work
的代码,每个调用thpool_add_work
一些内存(分配作业记录以添加到队列中),因此随着循环永远运行,它有时会耗尽内存也就不足为奇了。 您还将在最内部的循环内分配内存,这样也将有助于耗尽所有内存。
本质上,在内部循环中,您为args_struct
分配了16个字节(假定int为4), thpool_add_work
也分配了12个字节(出于对齐目的,可能舍入为16个字节)。
可以想象,这对您的4个嵌套循环(也可以无限运行)加起来很多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.