Fix clang-tidy
[alexxy/gromacs.git] / src / gromacs / utility / tests / mutex.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief Tests for gmx::Mutex
37  *
38  * These tests ensure that basic mutual-exclusion properties hold.
39  * Note that no testing can prove there isn't a bug, but if one
40  * exists, then these tests might expose one.
41  *
42  * In particular, try_lock can be implemented differently on different
43  * platforms, or with different default mutex types, so we should
44  * check that the behaviour continues to conform with the thread-MPI
45  * documentation.
46  *
47  * \author Mark Abraham <mark.j.abraham@gmail.com>
48  * \ingroup module_utility
49  */
50
51 #include "gmxpre.h"
52
53 #include "gromacs/utility/mutex.h"
54
55 #include "config.h"
56
57 #include <future>
58
59 #include <gtest/gtest.h>
60
61
62 namespace gmx
63 {
64 namespace test
65 {
66 namespace
67 {
68
69 //! Convenience definition.
70 using Lock = gmx::lock_guard<Mutex>;
71
72 TEST(MutexBasicTest, CanBeMade)
73 {
74     Mutex m;
75 }
76
77 TEST(MutexBasicTest, CanBeLocked)
78 {
79     Mutex m;
80     ASSERT_NO_THROW(m.lock());
81     m.unlock();
82 }
83
84 TEST(MutexBasicTest, CanBeTryLocked)
85 {
86     Mutex m;
87     ASSERT_TRUE(m.try_lock());
88     m.unlock();
89 }
90
91 TEST(MutexBasicTest, CanBeUsedInLockGuard)
92 {
93     Mutex m;
94     Lock  g(m);
95 }
96
97 //! A shared value for a mutex to protect
98 int g_sharedValue;
99 //! A mutex to protect a shared value
100 Mutex g_sharedValueMutex;
101
102 //! Function type for asynchronous tasks.
103 using TaskType = std::function<int(void)>;
104
105 //! A task that just does work.
106 int updateSharedValue()
107 {
108     return ++g_sharedValue;
109 }
110
111 //! A task that does work after it gets the mutex.
112 int updateSharedValueWithLock()
113 {
114     Lock guard(g_sharedValueMutex);
115     return updateSharedValue();
116 }
117
118 //! A task that does work only if it can get the mutex immediately.
119 int updateSharedValueWithTryLock()
120 {
121     // Special return value to signal when work was not done because
122     // the lock was not acquired.
123     int result = -1;
124     if (g_sharedValueMutex.try_lock())
125     {
126         result = updateSharedValue();
127         g_sharedValueMutex.unlock();
128     }
129     return result;
130 }
131
132 /*! \brief Parameterized test fixture.
133  *
134  * Checks that different launch policies work. In further tests of
135  * mutual exclusion, we need to specify std::thread::async, to require
136  * that a thread actually launched. The default policy permits the
137  * std:: implementation to avoid launching a thread, and at least the
138  * behaviour of thread-MPI try_lock also varies with the threading
139  * implementation underlying it. */
140 class DifferentTasksTest : public ::testing::TestWithParam<TaskType>
141 {
142 public:
143     DifferentTasksTest() { g_sharedValue = 0; }
144     //! Check the results
145     void checkResults()
146     {
147         int result = 0;
148         EXPECT_NO_THROW(result = futureResult_.get()) << "Future should not contain an exception";
149         EXPECT_EQ(1, result) << "Task should have run";
150         EXPECT_EQ(1, g_sharedValue) << "Shared value should be updated";
151     }
152     //! Contains the result the task returns.
153     std::future<int> futureResult_;
154 };
155
156 TEST_P(DifferentTasksTest, StdAsyncWorksWithDefaultPolicy)
157 {
158     auto task = GetParam();
159     EXPECT_NO_THROW(futureResult_ = std::async(task)) << "Async should succeed";
160     checkResults();
161 }
162
163 TEST_P(DifferentTasksTest, StdAsyncWorksWithAsyncLaunchPolicy)
164 {
165     auto task = GetParam();
166     EXPECT_NO_THROW(futureResult_ = std::async(std::launch::async, task)) << "Async should succeed";
167     checkResults();
168 }
169
170 TEST_P(DifferentTasksTest, StdAsyncWorksWithDeferredLaunchPolicy)
171 {
172     auto task = GetParam();
173     EXPECT_NO_THROW(futureResult_ = std::async(std::launch::deferred, task))
174             << "Async should succeed";
175     checkResults();
176 }
177
178 // Test that the different launch policies work with the different tasks
179 INSTANTIATE_TEST_CASE_P(WithAndWithoutMutex,
180                         DifferentTasksTest,
181                         ::testing::Values(updateSharedValue,
182                                           updateSharedValueWithLock,
183                                           updateSharedValueWithTryLock));
184
185 TEST(MutexTaskTest, MutualExclusionWorksWithLock)
186 {
187     g_sharedValue = 0;
188     std::future<int> result;
189     {
190         // Hold the mutex, launch a lock attempt on another
191         // thread, check that the shared value isn't changed, then
192         // release the mutex by leaving the scope, after which the
193         // other thread's lock can get the mutex.
194         Lock guard(g_sharedValueMutex);
195         result = std::async(std::launch::async, updateSharedValueWithLock);
196         EXPECT_EQ(0, g_sharedValue) << "Task should not have run yet";
197     }
198     EXPECT_EQ(1, result.get()) << "Task should have run";
199     EXPECT_EQ(1, g_sharedValue) << "Shared value should be updated";
200 }
201
202 TEST(MutexTaskTest, MutualExclusionWorksWithTryLockOnOtherThread)
203 {
204     g_sharedValue = 0;
205     {
206         // Hold the mutex, launch a try_lock attempt on another
207         // thread, check that the shared value isn't changed, then
208         // make sure the try_lock attempt has returned, double check
209         // that the shared value isn't changed, and release the mutex
210         // by leaving the scope.
211         Lock guard(g_sharedValueMutex);
212         auto result = std::async(std::launch::async, updateSharedValueWithTryLock);
213         EXPECT_EQ(0, g_sharedValue) << "Data race detected";
214         EXPECT_EQ(-1, result.get()) << "The try_lock should fail";
215         EXPECT_EQ(0, g_sharedValue) << "Task should not have run";
216     }
217     EXPECT_EQ(0, g_sharedValue) << "Mutex release can't affect the protected value";
218 }
219
220 TEST(MutexTaskTest, MutualExclusionWorksWithTryLockOnSameThread)
221 {
222     g_sharedValue        = 0;
223     int finalSharedValue = GMX_NATIVE_WINDOWS ? 1 : 0;
224     {
225         // Hold the mutex and launch a try_lock attempt on this
226         // thread. Behaviour then varies with the implementation
227         // underlying thread-MPI.
228         Lock guard(g_sharedValueMutex);
229         int  result = updateSharedValueWithTryLock();
230         if (GMX_NATIVE_WINDOWS)
231         {
232             EXPECT_EQ(1, result) << "The try_lock should succeed";
233             EXPECT_EQ(finalSharedValue, g_sharedValue) << "Task should have run";
234         }
235         else
236         {
237             EXPECT_EQ(-1, result) << "The try_lock should fail";
238             EXPECT_EQ(finalSharedValue, g_sharedValue) << "Task should not have run";
239         }
240     }
241     EXPECT_EQ(finalSharedValue, g_sharedValue) << "Mutex release can't affect the protected value";
242 }
243
244 } // namespace
245 } // namespace test
246 } // namespace gmx