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