-
Notifications
You must be signed in to change notification settings - Fork 294
/
thread_id_map.cc
86 lines (68 loc) · 2.12 KB
/
thread_id_map.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt.
// Contact: khmer-project@idyll.org
//
#if defined (__linux__)
# include <unistd.h>
# include <sys/syscall.h>
#endif
#include "thread_id_map.hh"
namespace khmer
{
ThreadIDMap::
ThreadIDMap( uint32_t number_of_threads )
: _number_of_threads( number_of_threads ),
_thread_counter( 0 ),
_tid_map_spin_lock( 0 )
{
if (0 == number_of_threads) {
throw InvalidNumberOfThreadsRequested( );
}
}
ThreadIDMap::
~ThreadIDMap( )
{
_thread_id_map.clear( );
}
uint32_t const
ThreadIDMap::
get_thread_id( )
{
#if defined (__linux__)
// Note: No error handling because this call always succeeds, allegedly.
pid_t native_thread_id = syscall( SYS_gettid );
std:: map< pid_t, uint32_t > :: iterator match;
#elif defined (__APPLE__) && defined (__MACH__)
// TODO? Error handling.
mach_port_t native_thread_id = pthread_mach_thread_np( pthread_self( ) );
std:: map< mach_port_t, uint32_t > :: iterator match;
#else
// TODO? Error handling.
pthread_t native_thread_id = pthread_self( );
std:: map< pthread_t, uint32_t > :: iterator match;
#endif
while (!__sync_bool_compare_and_swap( &_tid_map_spin_lock, 0, 1 ));
match = _thread_id_map.find( native_thread_id );
if (match == _thread_id_map.end( )) {
uint32_t thread_id;
thread_id = _thread_counter++;
try {
if (_number_of_threads < _thread_counter) {
throw TooManyThreads( );
}
_thread_id_map[ native_thread_id ] = thread_id;
} catch (...) {
_thread_counter--;
__sync_bool_compare_and_swap( &_tid_map_spin_lock, 1, 0 );
throw;
}
__sync_bool_compare_and_swap( &_tid_map_spin_lock, 1, 0 );
return thread_id;
}
__sync_bool_compare_and_swap( &_tid_map_spin_lock, 1, 0 );
return match->second;
} // get_thread_id
} // namespace khmer
// vim: set ft=cpp sts=4 sw=4 tw=79: