Created
September 3, 2012 15:16
-
-
Save preble/3610014 to your computer and use it in GitHub Desktop.
Test thread safety of random number generators.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Testing thread safety of rand() and random(); for more see: | |
// http://adampreble.net/blog/2012/09/mtrandom-an-objective-c-random-number-generator/ | |
// Created by Adam Preble on 9/3/12 | |
// Copyright (c) 2012 Adam Preble. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#if 1 | |
#define test_srandom srandom | |
#define test_random random | |
#else | |
#define test_srandom srand | |
#define test_random rand | |
#endif | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSMutableArray *allResults = [[NSMutableArray alloc] init]; | |
dispatch_group_t group = dispatch_group_create(); | |
dispatch_queue_t workQueue = dispatch_queue_create("net.adampreble.randomtest.work", DISPATCH_QUEUE_CONCURRENT); | |
dispatch_queue_t resultQueue = dispatch_queue_create("net.adampreble.randomtest.results", DISPATCH_QUEUE_SERIAL); | |
int numThreads = 4; | |
for (int i = 0; i < numThreads; i++) | |
{ | |
dispatch_group_async(group, workQueue, ^{ | |
NSMutableArray *numbers = [[NSMutableArray alloc] init]; | |
test_srandom(5); | |
for (int i = 0; i < 5; i++) | |
{ | |
[numbers addObject:@(test_random())]; | |
usleep(1); | |
} | |
dispatch_group_async(group, resultQueue, ^{ | |
[allResults addObject:numbers]; | |
NSLog(@"%@", [numbers componentsJoinedByString:@", "]); | |
}); | |
}); | |
} | |
dispatch_group_wait(group, DISPATCH_TIME_FOREVER); | |
for (NSUInteger i = 1; i < allResults.count; i++) | |
{ | |
if ([allResults[0] isEqual:allResults[i]] == NO) | |
{ | |
NSLog(@"Not thread safe!"); | |
return 1; | |
} | |
} | |
NSLog(@"Thread safe -- this time!"); | |
} | |
return 0; | |
} | |
/* Sample output: | |
RandomTest[58269:1703] 590011675, 2131925610, 940455586, 976522863, 62604080 | |
RandomTest[58269:1703] 678669015, 1653846685, 1854676444, 1374022803, 1236797572 | |
RandomTest[58269:1703] 590011675, 99788765, 1323721571, 2068056359, 99788765 | |
RandomTest[58269:1703] 590011675, 2131925610, 171864072, 317159276, 171035632 | |
RandomTest[58269:303] Not thread safe! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment