Last active
April 6, 2017 13:48
-
-
Save cramja/d2d1aa80e6eb2ddcf4dd to your computer and use it in GitHub Desktop.
clang++ -std=c++14 example.cpp -o ex.out -lpthread
This file contains 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
// A simple mutex-sharing scheme. | |
#include <assert.h> | |
#include <cstdlib> | |
#include <iostream> | |
#include <mutex> | |
#include <thread> | |
using namespace std; | |
int num_mtx = 10; | |
int num_grabs = 1000; | |
int num_threads = 100; | |
mutex *mtxs; | |
// Get a random lock candidate above a particular lock index. | |
// lo = lower bound index, inclusive | |
// hi = upper bound index, exclusive | |
int lock_candidate(int lo, int hi) { | |
assert(lo < hi); | |
assert(hi <= num_mtx); | |
int r = rand() % (((hi - lo) - 1)); | |
return r + lo; | |
} | |
// Acquire lock on a mutex @ index `lock`. | |
void get_lock(int lock) { | |
assert(lock < num_mtx && lock >= 0); | |
// This will block on lock() if the lock is not available. | |
mtxs[lock].lock(); | |
} | |
void release_lock(int lock) { | |
assert(lock < num_mtx && lock >= 0); | |
mtxs[lock].unlock(); | |
} | |
// Main method for a thread. | |
void tmain(int id) { | |
printf("Thread %d starting\n", id); | |
for (int i = 0; i < num_grabs; ++i) { | |
int l1; | |
int l2; | |
l1 = lock_candidate(0, num_mtx - 1); | |
printf("Thread %d wants first lock %d\n", id, l1); | |
get_lock(l1); | |
l2 = lock_candidate(l1 + 1, num_mtx); | |
printf("Thread %d got lock on %d, wants %d\n", id, l1, l2); | |
get_lock(l2); | |
printf("Thread %d got lock on %d\n", id, l2); | |
release_lock(l2); | |
release_lock(l1); | |
printf("Thread %d released %d, %d\n", id, l1, l2); | |
} | |
printf("Thread %d finished\n", id); | |
} | |
int main() { | |
// Initialize locks. | |
mtxs = new mutex[num_mtx](); | |
// Create threads. | |
thread **threads = new thread*[num_threads]; | |
for (int i = 0; i < num_threads; ++i) { | |
// Call to constructor will start the thread. | |
threads[i] = new thread(tmain, i); | |
} | |
printf("All threads created\n"); | |
for (int i = 0; i < num_threads; ++i) { | |
threads[i]->join(); | |
} | |
printf("All threads completed\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment