854978efcb3ac92b2e2d0a952ac69787b8a17b7b
[framework/web/wrt-commons.git] / tests / core / test_semaphore.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file        test_semaphore.cpp
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version     1.0
20  * @brief       This file is the implementation file of semaphore tests
21  */
22 #include <dpl/test/test_runner.h>
23 #include <dpl/lexical_cast.h>
24 #include <dpl/semaphore.h>
25 #include <dpl/thread.h>
26 #include <dpl/log/log.h>
27 #include <string>
28 #include <ctime>
29
30 RUNNER_TEST_GROUP_INIT(DPL)
31
32 class SemaphoreThread
33     : public DPL::Thread
34 {
35     int m_delta;
36     int m_times;
37     int *m_value;
38     std::string m_semaphoreName;
39
40 public:
41     SemaphoreThread(int delta,
42                     int times,
43                     int *value,
44                     const std::string &semaphoreName)
45         : m_delta(delta),
46           m_times(times),
47           m_value(value),
48           m_semaphoreName(semaphoreName)
49     {
50     }
51
52 protected:
53     virtual int ThreadEntry()
54     {
55         DPL::Semaphore semaphore(m_semaphoreName);
56
57         for (int i = 0; i < m_times; ++i)
58         {
59             // Take scoped semaphore lock
60             DPL::Semaphore::ScopedLock lock(&semaphore);
61             *m_value += m_delta;
62         }
63
64         return 0;
65     }
66 };
67
68 RUNNER_TEST(Semaphore_NamedIncrementDecrement)
69 {
70     std::string semaphoreName =
71         "dpl_test_semaphore_" +
72         DPL::lexical_cast<std::string>(std::time(NULL));
73
74     int value = 0;
75     SemaphoreThread threadA(-1, 10000, &value, semaphoreName);
76     SemaphoreThread threadB(+1, 10000, &value, semaphoreName);
77
78     threadA.Run();
79     threadB.Run();
80
81     threadA.Quit();
82     threadB.Quit();
83
84     RUNNER_ASSERT_MSG(value == 0, "Final value is: " << value);
85 }