Skip to content

Commit 7594c4d

Browse files
authored
Merge pull request #11 from ganlvtech/master
Fix #10: Fix pthread_spin_unlock. Add new test case
2 parents c792861 + 400d5a3 commit 7594c4d

File tree

2 files changed

+24
-23
lines changed

2 files changed

+24
-23
lines changed

pthread_spin_lock.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ static inline int pthread_spin_trylock(pthread_spinlock_t *lock) {
3434
}
3535

3636
static inline int pthread_spin_unlock(pthread_spinlock_t *lock) {
37-
__asm__ __volatile__ ("" ::: "memory");
38-
*lock = 0;
37+
__sync_sub_and_fetch(lock, 1);
3938
return 0;
4039
}
4140

unittest/test_mutex.cpp

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,49 +7,51 @@
77

88
struct GlobalData
99
{
10-
std::map<int, int> g_fd_to_file;
11-
PthreadRwMutex g_file_to_shadowzip_mutex;
10+
std::map<int, int> g_fd_to_file;
11+
PthreadRwMutex g_file_to_shadowzip_mutex;
1212
};
1313
#define g_global_data (LeakSingleton<GlobalData, 0>::instance())
1414

15-
int count;
15+
int a = 0;
16+
int b = 0;
17+
int c = 0;
18+
int d = 0;
1619
const size_t THREAD_NUM = 6;
1720

1821
void increment_count()
1922
{
20-
{
21-
PthreadWriteGuard guard(g_global_data->g_file_to_shadowzip_mutex);
22-
count = count + 1;
23-
std::cout << "write count:" << count << std::endl;
24-
}
23+
PthreadWriteGuard guard(g_global_data->g_file_to_shadowzip_mutex);
24+
a++;
25+
b++;
26+
c++;
27+
d++;
2528
}
2629

27-
long long get_count()
30+
void verify_count()
2831
{
29-
long long c;
30-
{
31-
PthreadReadGuard guard(g_global_data->g_file_to_shadowzip_mutex);
32-
c = count;
33-
std::cout << "read count:" << count << std::endl;
34-
}
35-
return (c);
32+
PthreadReadGuard guard(g_global_data->g_file_to_shadowzip_mutex);
33+
if (a != b || a != c || a != d) {
34+
std::cout << "pthread unit test failed: " << a << " " << b << " " << c << " " << d << std::endl;
35+
}
3636
}
3737

3838
//-----------------------------------------------------------------------
3939
void *thread_proc(void *arg)
4040
{
41+
int thread_id = (int) (intptr_t) arg;
42+
std::cout << "thread " << thread_id << " started" << std::endl;
4143
for(int i = 0; i < 1000000; i++){
42-
increment_count();
43-
get_count();
44-
}
45-
44+
increment_count();
45+
verify_count();
46+
}
47+
std::cout << "thread " << thread_id << " end" << std::endl;
4648
pthread_exit(0);
4749
return 0;
4850
}
4951

5052
int main(int argc, char *argv[])
5153
{
52-
LeakSingleton<GlobalData, 0>::init();
54+
LeakSingleton<GlobalData, 0>::init();
5355
pthread_t threadids[THREAD_NUM];
5456
for(size_t i = 0; i < THREAD_NUM; i++)
5557
{

0 commit comments

Comments
 (0)