1 | /* |
2 | * Copyright 2016-present Facebook, Inc. |
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 | #include <folly/portability/PThread.h> |
18 | |
19 | #include <folly/portability/GTest.h> |
20 | |
21 | #include <atomic> |
22 | |
23 | TEST(PThreadTest, pthread_create_and_join) { |
24 | static std::atomic<bool> hasRun{false}; |
25 | static std::atomic<int32_t> argPassedIn{0}; |
26 | auto mainFunc = [](void* arg) -> void* { |
27 | hasRun = true; |
28 | argPassedIn = (int32_t) reinterpret_cast<uintptr_t>(arg); |
29 | return nullptr; |
30 | }; |
31 | |
32 | pthread_t thread; |
33 | EXPECT_EQ(pthread_create(&thread, nullptr, mainFunc, (void*)53), 0); |
34 | EXPECT_EQ(pthread_join(thread, nullptr), 0); |
35 | EXPECT_TRUE(hasRun); |
36 | EXPECT_EQ(argPassedIn, 53); |
37 | } |
38 | |
39 | TEST(PThreadTest, pthread_join_return_value) { |
40 | static std::atomic<bool> hasRun{false}; |
41 | auto mainFunc = [](void*) -> void* { |
42 | hasRun = true; |
43 | return (void*)5; |
44 | }; |
45 | |
46 | pthread_t thread; |
47 | EXPECT_EQ(pthread_create(&thread, nullptr, mainFunc, nullptr), 0); |
48 | void* exitCode = nullptr; |
49 | EXPECT_EQ(pthread_join(thread, &exitCode), 0); |
50 | EXPECT_EQ(exitCode, (void*)5); |
51 | EXPECT_TRUE(hasRun); |
52 | } |
53 | |
54 | TEST(PThreadTest, pthread_equal) { |
55 | auto self = pthread_self(); |
56 | EXPECT_NE(pthread_equal(self, self), 0); |
57 | |
58 | auto mainFunc = [](void*) -> void* { return nullptr; }; |
59 | pthread_t thread; |
60 | EXPECT_EQ(pthread_create(&thread, nullptr, mainFunc, nullptr), 0); |
61 | EXPECT_EQ(pthread_equal(thread, self), 0); |
62 | } |
63 | |
64 | TEST(PThreadTest, pthread_self_on_pthread_thread) { |
65 | static std::atomic<bool> hasRun{false}; |
66 | static pthread_t otherSelf; |
67 | auto mainFunc = [](void*) -> void* { |
68 | hasRun = true; |
69 | otherSelf = pthread_self(); |
70 | return nullptr; |
71 | }; |
72 | |
73 | pthread_t thread; |
74 | EXPECT_EQ(pthread_create(&thread, nullptr, mainFunc, nullptr), 0); |
75 | EXPECT_EQ(pthread_join(thread, nullptr), 0); |
76 | EXPECT_NE(pthread_equal(otherSelf, thread), 0); |
77 | EXPECT_TRUE(hasRun); |
78 | } |
79 | |