xref: /freebsd/contrib/llvm-project/libcxx/src/random_shuffle.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
1349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric 
981ad6265SDimitry Andric #include <algorithm>
1081ad6265SDimitry Andric #include <random>
1181ad6265SDimitry Andric 
125ffd83dbSDimitry Andric #ifndef _LIBCPP_HAS_NO_THREADS
1381ad6265SDimitry Andric #  include <mutex>
145ffd83dbSDimitry Andric #  if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)
155ffd83dbSDimitry Andric #    pragma comment(lib, "pthread")
165ffd83dbSDimitry Andric #  endif
175ffd83dbSDimitry Andric #endif
185ffd83dbSDimitry Andric 
195ffd83dbSDimitry Andric _LIBCPP_BEGIN_NAMESPACE_STD
205ffd83dbSDimitry Andric 
215ffd83dbSDimitry Andric #ifndef _LIBCPP_HAS_NO_THREADS
2281ad6265SDimitry Andric static constinit __libcpp_mutex_t __rs_mut = _LIBCPP_MUTEX_INITIALIZER;
235ffd83dbSDimitry Andric #endif
245ffd83dbSDimitry Andric unsigned __rs_default::__c_ = 0;
255ffd83dbSDimitry Andric 
26*cb14a3feSDimitry Andric __rs_default::__rs_default() {
275ffd83dbSDimitry Andric #ifndef _LIBCPP_HAS_NO_THREADS
285ffd83dbSDimitry Andric   __libcpp_mutex_lock(&__rs_mut);
295ffd83dbSDimitry Andric #endif
305ffd83dbSDimitry Andric   __c_ = 1;
315ffd83dbSDimitry Andric }
325ffd83dbSDimitry Andric 
33*cb14a3feSDimitry Andric __rs_default::__rs_default(const __rs_default&) { ++__c_; }
345ffd83dbSDimitry Andric 
35*cb14a3feSDimitry Andric __rs_default::~__rs_default() {
365ffd83dbSDimitry Andric #ifndef _LIBCPP_HAS_NO_THREADS
375ffd83dbSDimitry Andric   if (--__c_ == 0)
385ffd83dbSDimitry Andric     __libcpp_mutex_unlock(&__rs_mut);
395ffd83dbSDimitry Andric #else
405ffd83dbSDimitry Andric   --__c_;
415ffd83dbSDimitry Andric #endif
425ffd83dbSDimitry Andric }
435ffd83dbSDimitry Andric 
44*cb14a3feSDimitry Andric __rs_default::result_type __rs_default::operator()() {
455ffd83dbSDimitry Andric   static mt19937 __rs_g;
465ffd83dbSDimitry Andric   return __rs_g();
475ffd83dbSDimitry Andric }
485ffd83dbSDimitry Andric 
49*cb14a3feSDimitry Andric __rs_default __rs_get() { return __rs_default(); }
505ffd83dbSDimitry Andric 
515ffd83dbSDimitry Andric _LIBCPP_END_NAMESPACE_STD
52