tizen 2.4 release
[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 <string>
27 #include <ctime>
28
29 RUNNER_TEST_GROUP_INIT(DPL)
30
31 class SemaphoreThread :
32     public DPL::Thread
33 {
34     int m_delta;
35     int m_times;
36     int *m_value;
37     std::string m_semaphoreName;
38
39   public:
40     SemaphoreThread(int delta,
41                     int times,
42                     int *value,
43                     const std::string &semaphoreName) :
44         m_delta(delta),
45         m_times(times),
46         m_value(value),
47         m_semaphoreName(semaphoreName)
48     {}
49
50   protected:
51     virtual int ThreadEntry()
52     {
53         DPL::Semaphore semaphore(m_semaphoreName);
54
55         for (int i = 0; i < m_times; ++i) {
56             // Take scoped semaphore lock
57             DPL::Semaphore::ScopedLock lock(&semaphore);
58             *m_value += m_delta;
59         }
60
61         return 0;
62     }
63 };
64
65 /*
66 Name: Semaphore_NamedIncrementDecrement
67 Description: Checks if semaphore are working
68 Expected: value should not change after all
69 */
70 RUNNER_TEST(Semaphore_NamedIncrementDecrement)
71 {
72     std::string semaphoreName =
73         "dpl_test_semaphore_" +
74         DPL::lexical_cast<std::string>(std::time(NULL));
75
76     int value = 0;
77     SemaphoreThread threadA(-1, 10000, &value, semaphoreName);
78     SemaphoreThread threadB(+1, 10000, &value, semaphoreName);
79
80     threadA.Run();
81     threadB.Run();
82
83     threadA.Quit();
84     threadB.Quit();
85
86     RUNNER_ASSERT_MSG(value == 0, "Final value is: " << value);
87 }