]> git.saurik.com Git - apple/objc4.git/blob - test/synchronized-counter.m
objc4-756.2.tar.gz
[apple/objc4.git] / test / synchronized-counter.m
1 // TEST_CONFIG
2
3 #include "test.h"
4
5 #include <stdlib.h>
6 #include <pthread.h>
7 #include <objc/runtime.h>
8 #include <objc/objc-sync.h>
9 #include <Foundation/NSObject.h>
10 #include <System/pthread_machdep.h>
11
12 // synchronized stress test
13 // Single locked counter incremented by many threads.
14
15 #if defined(__arm__)
16 #define THREADS 16
17 #define COUNT 1024*24
18 #else
19 // 64 / 1024*24 test takes about 20s on 4x2.6GHz Mac Pro
20 #define THREADS 64
21 #define COUNT 1024*24
22 #endif
23
24 static id lock;
25 static int count;
26
27 static void *threadfn(void *arg)
28 {
29 int n, d;
30 int depth = 1 + (int)(intptr_t)arg % 4;
31
32 for (n = 0; n < COUNT; n++) {
33 // Lock
34 for (d = 0; d < depth; d++) {
35 int err = objc_sync_enter(lock);
36 testassert(err == OBJC_SYNC_SUCCESS);
37 }
38
39 // Increment
40 count++;
41
42 // Unlock
43 for (d = 0; d < depth; d++) {
44 int err = objc_sync_exit(lock);
45 testassert(err == OBJC_SYNC_SUCCESS);
46 }
47 }
48
49 // Verify lack of objc pthread data (should have used sync fast cache)
50 #ifdef __PTK_FRAMEWORK_OBJC_KEY0
51 testassert(! pthread_getspecific(__PTK_FRAMEWORK_OBJC_KEY0));
52 #endif
53
54 return NULL;
55 }
56
57 int main()
58 {
59 pthread_t threads[THREADS];
60 int t;
61 int err;
62
63 lock = [[NSObject alloc] init];
64
65 // Verify objc pthread data on this thread (from +initialize)
66 // Worker threads shouldn't have any because of sync fast cache.
67 #ifdef __PTK_FRAMEWORK_OBJC_KEY0
68 testassert(pthread_getspecific(__PTK_FRAMEWORK_OBJC_KEY0));
69 #endif
70
71 // Start the threads
72 for (t = 0; t < THREADS; t++) {
73 pthread_create(&threads[t], NULL, &threadfn, (void*)(intptr_t)t);
74 }
75
76 // Wait for threads to finish
77 for (t = 0; t < THREADS; t++) {
78 pthread_join(threads[t], NULL);
79 }
80
81 // Verify lock: should be available
82 // Verify count: should be THREADS*COUNT
83 err = objc_sync_enter(lock);
84 testassert(err == OBJC_SYNC_SUCCESS);
85 testassert(count == THREADS*COUNT);
86
87 succeed(__FILE__);
88 }