-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
57 lines (49 loc) · 1.44 KB
/
main.cpp
File metadata and controls
57 lines (49 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <cstdlib>
#include <pthread.h>
#include <stdio.h>
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif // EMSCRIPTEN
pthread_mutex_t lock;
void* crack( void* arg ) {
unsigned int id = *( static_cast<unsigned int*>( arg ) );
srand( id );
unsigned int key = -1;
while( true ) {
unsigned int v = rand();
if( v == ( v & key ) ) {
if( pthread_mutex_lock( &lock ) ) {
printf( "mutex lock failed\n" );
return nullptr;
}
printf( "thread=%u key=%x value=%x\n", id, key, v );
if( pthread_mutex_unlock( &lock ) ) {
printf( "mutex unlock failed\n" );
return nullptr;
}
key = key << 1;
}
}
}
int main() {
if( pthread_mutex_init( &lock, NULL ) != 0 ) {
printf( "mutex init failed\n" );
return -1;
}
pthread_t thread[2];
for( unsigned int i = 0; i < 2; ++i ) {
if( pthread_create( thread + i, nullptr, crack, static_cast<void*>( new unsigned int( i ) ) ) ) {
fprintf( stderr, "Failed to start thread.\n" );
}
}
// Emscripten needs to fall through and exit main.
#ifndef EMSCRIPTEN
// Wait for thread that will never exit.
for( unsigned int i = 0; i < 2; ++i ) {
if( pthread_join( thread[i], nullptr ) ) {
fprintf( stderr, "Failed to join thread.\n" );
}
}
#endif // EMSCRIPTEN
return 0;
}