pthread_test.cpp revision 14f19592ae7c819855052bcebc79de87069c2954
1/* 2 * Copyright (C) 2012 The Android Open Source Project 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 <gtest/gtest.h> 18 19#include <errno.h> 20#include <pthread.h> 21#include <unistd.h> 22 23TEST(pthread, pthread_key_create) { 24 pthread_key_t key; 25 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 26 ASSERT_EQ(0, pthread_key_delete(key)); 27 // Can't delete a key that's already been deleted. 28 ASSERT_EQ(EINVAL, pthread_key_delete(key)); 29} 30 31static void* IdFn(void* arg) { 32 return arg; 33} 34 35static void* SleepFn(void* arg) { 36 sleep(reinterpret_cast<unsigned int>(arg)); 37 return NULL; 38} 39 40static void* JoinFn(void* arg) { 41 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL)); 42} 43 44TEST(pthread, pthread_create) { 45 void* expected_result = reinterpret_cast<void*>(123); 46 // Can we create a thread? 47 pthread_t t; 48 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result)); 49 // If we join, do we get the expected value back? 50 void* result; 51 ASSERT_EQ(0, pthread_join(t, &result)); 52 ASSERT_EQ(expected_result, result); 53} 54 55TEST(pthread, pthread_no_join_after_detach) { 56 pthread_t t1; 57 ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(5))); 58 59 // After a pthread_detach... 60 ASSERT_EQ(0, pthread_detach(t1)); 61 62 // ...pthread_join should fail. 63 void* result; 64 ASSERT_EQ(EINVAL, pthread_join(t1, &result)); 65} 66 67TEST(pthread, pthread_no_op_detach_after_join) { 68 pthread_t t1; 69 ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(1))); 70 71 // If thread 2 is already waiting to join thread 1... 72 pthread_t t2; 73 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); 74 75 // ...a call to pthread_detach on thread 1 will "succeed"... 76 ASSERT_EQ(0, pthread_detach(t1)); 77 78 // ...but the join still goes ahead. 79 void* join_result; 80 ASSERT_EQ(0, pthread_join(t2, &join_result)); 81 ASSERT_EQ(EINVAL, reinterpret_cast<int>(join_result)); 82} 83 84TEST(pthread, pthread_join_self) { 85 void* result; 86 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), &result)); 87} 88