1 /* Test for open_memstream locking.
2 Copyright (C) 2017-2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 /* This test checks if concurrent writes to a FILE created with
20 open_memstream are correctly interleaved without loss or corruption
21 of data. Large number of concurrent fputc operations are used
22 and in the end the bytes written to the memstream buffer are
23 counted to see if they all got recorded.
25 This is a regression test to see if the single threaded stdio
26 optimization broke multi-threaded open_memstream usage. */
30 #include <support/check.h>
31 #include <support/xthread.h>
46 thread_func (void *closure
)
48 struct closure
*args
= closure
;
50 for (int i
= 0; i
< byte_count
; ++i
)
51 fputc (args
->b
, args
->fp
);
60 size_t buffer_length
= 0;
61 FILE *fp
= open_memstream (&buffer
, &buffer_length
);
63 FAIL_RET ("open_memstream: %m");
65 pthread_t threads
[thread_count
];
66 struct closure args
[thread_count
];
68 for (int i
= 0; i
< thread_count
; ++i
)
72 threads
[i
] = xpthread_create (NULL
, thread_func
, args
+ i
);
75 for (int i
= 0; i
< thread_count
; ++i
)
76 xpthread_join (threads
[i
]);
80 if (buffer_length
!= thread_count
* byte_count
)
81 FAIL_RET ("unexpected number of written bytes: %zu (should be %d)",
82 buffer_length
, thread_count
* byte_count
);
84 /* Verify that each thread written its unique character byte_count times. */
85 size_t counts
[thread_count
] = { 0, };
86 for (size_t i
= 0; i
< buffer_length
; ++i
)
88 if (buffer
[i
] < 'A' || buffer
[i
] >= 'A' + thread_count
)
89 FAIL_RET ("written byte at %zu out of range: %d", i
, buffer
[i
] & 0xFF);
90 ++counts
[buffer
[i
] - 'A'];
92 for (int i
= 0; i
< thread_count
; ++i
)
93 if (counts
[i
] != byte_count
)
94 FAIL_RET ("incorrect write count for thread %d: %zu (should be %d)", i
,
95 counts
[i
], byte_count
);
101 #include <support/test-driver.c>