5 #include <objc/runtime.h>
6 #include <objc/objc-sync.h>
7 #include <Foundation/Foundation.h>
9 // synchronized stress test
10 // 2-D grid of counters and locks.
11 // Each thread increments all counters some number of times.
13 // * thread picks a target [row][col]
14 // * thread locks all locks [row][0] to [row][col], possibly recursively
15 // * thread increments counter [row][col]
16 // * thread unlocks all of the locks
18 // 64 / 4 / 3 / 1024*8 test takes about 20s on 4x2.6GHz Mac Pro
24 static id locks[ROWS][COLS];
25 static int counts[ROWS][COLS];
28 static void *threadfn(void *arg)
31 int depth = 1 + (int)(intptr_t)arg % 4;
33 objc_registerThreadWithCollector();
35 for (n = 0; n < COUNT; n++) {
36 int rrr = rand() % ROWS;
37 int ccc = rand() % COLS;
39 for (rr = 0; rr < ROWS; rr++) {
40 int r = (rrr+rr) % ROWS;
41 for (cc = 0; cc < COLS; cc++) {
42 int c = (ccc+cc) % COLS;
46 // ... in that order to prevent deadlock
47 for (l = 0; l <= c; l++) {
48 for (d = 0; d < depth; d++) {
49 int err = objc_sync_enter(locks[r][l]);
50 testassert(err == OBJC_SYNC_SUCCESS);
54 // Increment count [r][c]
58 // ... in that order to increase contention
59 for (l = 0; l <= c; l++) {
60 for (d = 0; d < depth; d++) {
61 int err = objc_sync_exit(locks[r][l]);
62 testassert(err == OBJC_SYNC_SUCCESS);
74 pthread_t threads[THREADS];
77 for (r = 0; r < ROWS; r++) {
78 for (c = 0; c < COLS; c++) {
79 locks[r][c] = [[NSObject alloc] init];
84 for (t = 0; t < THREADS; t++) {
85 pthread_create(&threads[t], NULL, &threadfn, (void*)(intptr_t)t);
88 // Wait for threads to finish
89 for (t = 0; t < THREADS; t++) {
90 pthread_join(threads[t], NULL);
93 // Verify locks: all should be available
94 // Verify counts: all should be THREADS*COUNT
95 for (r = 0; r < ROWS; r++) {
96 for (c = 0; c < COLS; c++) {
97 int err = objc_sync_enter(locks[r][c]);
98 testassert(err == OBJC_SYNC_SUCCESS);
99 testassert(counts[r][c] == THREADS*COUNT);