1 /* Use the internal lock used by mbrtowc and mbrtoc32.
2 Copyright (C) 2019-2020 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2019-2020. */
19 /* Use a lock, so that no two threads can invoke mbtowc at the same time. */
22 mbtowc_unlocked (wchar_t *pwc
, const char *p
, size_t m
)
24 /* Put the hidden internal state of mbtowc into its initial state.
25 This is needed at least with glibc, uClibc, and MSVC CRT.
26 See <https://sourceware.org/bugzilla/show_bug.cgi?id=9674>. */
27 mbtowc (NULL
, NULL
, 0);
29 return mbtowc (pwc
, p
, m
);
32 /* Prohibit renaming this symbol. */
33 #undef gl_get_mbtowc_lock
35 #if defined _WIN32 && !defined __CYGWIN__
37 extern __declspec(dllimport
) CRITICAL_SECTION
*gl_get_mbtowc_lock (void);
40 mbtowc_with_lock (wchar_t *pwc
, const char *p
, size_t m
)
42 CRITICAL_SECTION
*lock
= gl_get_mbtowc_lock ();
45 EnterCriticalSection (lock
);
46 ret
= mbtowc_unlocked (pwc
, p
, m
);
47 LeaveCriticalSection (lock
);
52 #elif HAVE_PTHREAD_API /* AIX, IRIX, Cygwin */
55 # if defined _WIN32 || defined __CYGWIN__
58 pthread_mutex_t
*gl_get_mbtowc_lock (void);
60 # if HAVE_WEAK_SYMBOLS /* IRIX */
62 /* Avoid the need to link with '-lpthread'. */
63 # pragma weak pthread_mutex_lock
64 # pragma weak pthread_mutex_unlock
66 /* Determine whether libpthread is in use. */
67 # pragma weak pthread_mutexattr_gettype
68 /* See the comments in lock.h. */
69 # define pthread_in_use() \
70 (pthread_mutexattr_gettype != NULL || c11_threads_in_use ())
73 # define pthread_in_use() 1
77 mbtowc_with_lock (wchar_t *pwc
, const char *p
, size_t m
)
81 pthread_mutex_t
*lock
= gl_get_mbtowc_lock ();
84 if (pthread_mutex_lock (lock
))
86 ret
= mbtowc_unlocked (pwc
, p
, m
);
87 if (pthread_mutex_unlock (lock
))
93 return mbtowc_unlocked (pwc
, p
, m
);
98 extern mtx_t
*gl_get_mbtowc_lock (void);
101 mbtowc_with_lock (wchar_t *pwc
, const char *p
, size_t m
)
103 mtx_t
*lock
= gl_get_mbtowc_lock ();
106 if (mtx_lock (lock
) != thrd_success
)
108 ret
= mbtowc_unlocked (pwc
, p
, m
);
109 if (mtx_unlock (lock
) != thrd_success
)