[asterisk-commits] russell: trunk r38127 - /trunk/cli.c

asterisk-commits at lists.digium.com asterisk-commits at lists.digium.com
Sun Jul 23 08:19:16 MST 2006


Author: russell
Date: Sun Jul 23 10:19:16 2006
New Revision: 38127

URL: http://svn.digium.com/view/asterisk?rev=38127&view=rev
Log:
Merge team/russell/ast_cli_tls into the trunk.

This improves the performance of ast_cli() by not doing a heap memory
allocation and deallocation every single time the function is called. Instead,
a thread-specific buffer is allocatted the first time the function is called
and automatically free'd when the thread exits. Also note that this buffer will
only be allocatted in threads that actually call this function, which is 
probably only the threads spawned to service connected asterisk consoles.

This does introduce a new limitation on the maximum length of the resulting
string from the arguments passed to ast_cli. Previously there was no limit
since it was just allocating a buffer big enough every time the function was
called. The current buffer size is 16kB. If there is ever a case where we want
to print more than 16k characters in a single call to ast_cli(), this will have
to be increased.

Modified:
    trunk/cli.c

Modified: trunk/cli.c
URL: http://svn.digium.com/view/asterisk/trunk/cli.c?rev=38127&r1=38126&r2=38127&view=diff
==============================================================================
--- trunk/cli.c (original)
+++ trunk/cli.c Sun Jul 23 10:19:16 2006
@@ -50,22 +50,37 @@
 #include "editline/readline/readline.h"
 
 extern unsigned long global_fin, global_fout;
-	
+
+static pthread_key_t ast_cli_buf_key;
+static pthread_once_t ast_cli_buf_once = PTHREAD_ONCE_INIT;
+
+/*! \brief Maximum length of resulting strings in ast_cli() */
+#define AST_CLI_MAXSTRLEN   16384
+
+static void ast_cli_buf_key_create(void)
+{
+	pthread_key_create(&ast_cli_buf_key, free);
+}
+
 void ast_cli(int fd, char *fmt, ...)
 {
-	char *stuff;
+	char *buf;
 	int res;
 	va_list ap;
 
+	pthread_once(&ast_cli_buf_once, ast_cli_buf_key_create);
+	if (!(buf = pthread_getspecific(ast_cli_buf_key))) {
+		if (!(buf = ast_malloc(AST_CLI_MAXSTRLEN)))
+			return;
+		pthread_setspecific(ast_cli_buf_key, buf);
+	}
+
 	va_start(ap, fmt);
-	res = vasprintf(&stuff, fmt, ap);
+	res = vsnprintf(buf, AST_CLI_MAXSTRLEN, fmt, ap);
 	va_end(ap);
-	if (res == -1) {
-		ast_log(LOG_ERROR, "Memory allocation failure\n");
-	} else {
-		ast_carefulwrite(fd, stuff, strlen(stuff), 100);
-		free(stuff);
-	}
+
+	if (res > 0)
+		ast_carefulwrite(fd, buf, strlen(buf), 100);
 }
 
 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);



More information about the asterisk-commits mailing list