From 50eb4bf53a1d96a76687b83ca1518d0085f073af Mon Sep 17 00:00:00 2001 From: Matt Pharr Date: Thu, 21 Jun 2012 14:41:53 -0700 Subject: [PATCH] Change print() implementation to accumulate string locally before printing. The string to be printed is accumulated into a local buffer before being sent to puts(). This ensure that if multiple threads are running and printing at the same time, their output won't be interleaved (across individual print statements-- it still may be interleaved across different print statements, just like in C). Issue #293. --- builtins/builtins.c | 66 ++++++++++++++++++++++++++++++++------------- 1 file changed, 47 insertions(+), 19 deletions(-) diff --git a/builtins/builtins.c b/builtins/builtins.c index 8e1a5624..962cea23 100644 --- a/builtins/builtins.c +++ b/builtins/builtins.c @@ -59,22 +59,39 @@ #include #include #include +#include typedef int Bool; -#define PRINT_SCALAR(fmt, type) \ - printf(fmt, *((type *)ptr)); \ +#define PRINT_BUF_SIZE 4096 + +#define APPEND(str) \ + do { \ + int offset = bufp - &printString[0]; \ + *bufp = '\0'; \ + strncat(bufp, str, PRINT_BUF_SIZE-offset); \ + bufp += strlen(str); \ + if (bufp >= &printString[PRINT_BUF_SIZE]) \ + goto done; \ + } while (0) /* eat semicolon */ + + +#define PRINT_SCALAR(fmt, type) \ + sprintf(tmpBuf, fmt, *((type *)ptr)); \ + APPEND(tmpBuf); \ break #define PRINT_VECTOR(fmt, type) \ - putchar('['); \ + *bufp++ = '['; \ + if (bufp == &printString[PRINT_BUF_SIZE]) break; \ for (int i = 0; i < width; ++i) { \ /* only print the value if the current lane is executing */ \ if (mask & (1ull<