c - Synchronizing threads, mutex -
i'm trying homework i'm stuck these threads.. function called when thread created:
size_t* mines, gold = 0, gold_collected = 0; pthread_mutex_t mine_mutex; int last_mine = 0; void* dig(void *mine_start) { int current_worker = (int)mine_start; int mine = (int)mine_start; // printf("hello, it's me, thread %d\n", current_worker); while(gold != 0) { if(mine > last_mine - 1) { mine = 0; } pthread_mutex_lock(&mine_mutex); if(mines[mine] != 0) { //printf("all gold %zd\n", gold); //printf("gold in mine %zd number %d\n", mines[mine], mine); printf("worker %d entered mine %d\n", current_worker, mine); gold -= 10; mines[mine] -= 10; gold_collected += 10; //sleep(1); } pthread_mutex_unlock(&mine_mutex); ++mine; } pthread_exit(null); } my problem when have 5 mines , 2 workers, 1 worker gets in mine , digs gold. how can rotate threads of them can dig mine?
if want 1 miner per mine, have more miners mines, have decide idle miners when mines in use. furthermore, if have mutex per mine, , tries take first mutex, 1 miner win, , others still block. can use try lock, miners busy wait when mines full.
you use semaphore initialized number of mines. each miner, upon acquiring semaphore know there mine available them, wouldn't know one. use single mutex protect of mines' in-use state. after acquiring semaphore, acquire mutex, hunt available mine, mark in-use, release mutex , start mining. then, when done, re-acquire mutex, mark mine available, release mutex, , release semaphore.
finally, instead of semaphore, use condition variable , mutex. acquire mutex, , hunt available mine. if cannot find one, block on condvar. if find one, mark in use, release mutex, , start mining. when done, re-acquire mutex, mark mine available, signal condvar, , release mutex. thread awakes on condvar have automatically re-acquired mutex , should loop around , re-hunt available mine. in case, should sufficient signal condvar instead of broadcasting; although broadcasting can safer.
also, once have parallel miners, you're going have rethink global gold , gold_collected. since miners doing actual mining without holding mutex, cannot update these globals while mining. should keep local tally of amount of gold mined, , update global once mutex has been re-acquired. maybe gold can deducted before miner enters mine, , gold_collected updated after leaving mine (both while holding mutex). it's little iffy reading gold when not holding mutex, since change underneath you...
Comments
Post a Comment