This is the idea of a mutex: keep the other person out while you do your thing.
This is a semaphore:
Just kidding, this is a real semaphore:
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
Semamore sem;
Stack s; // Thread Safe Stack
void* transaction_listener(void* arg) {
while(1) {
semm_post(&sem); // increments the semamore
stack_push(&s, get_transaction());
}
}
void* transaction_verifier(void* arg) {
while(1) {
semm_wait(&sem); // decrements the semamore
transaction = stack_pop(&s);
verify(transaction);
}
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, transaction_listener, NULL);
pthread_create(&tid2, NULL, transaction_verifier, NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
exit(0);
}
typedef struct {
int value, max_value;
pthread_mutext_t m;
pthread_cond_t cv;
} Semamore;
max_value
is reached
max_value
?if(!condition)
pthread_cond_wait(&cv, &mutex);
What is wrong with the code above?
(hint: what if we get woken up while condition
is still true?)
What does a barrier look like? Glad you asked.
void * entry_point(void *arg)
{
// final_matrix = initial_matrix * initial_matrix
for(int row in thread_range)
for(int col = 0; col < COLS; ++col)
DotProduct(row, col, initial_matrix, final_matrix);
// Make sure the threads stop before moving on
int rc = pthread_barrier_wait(&barr);
//Check for error
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\n");
exit(-1);
}
// initial matrix = final_matrix * final_matrix
for(int row in thread_range)
for(int col = 0; col < COLS; ++col)
DotProduct(row, col, final_matrix, initial_matrix);
}
More information is in the coursebook.
Remember CS 124/225! Appending to the head of a linked list, other edge cases, etc…
cond_wait
.PTHREAD_MUTEX_INITIALIZER
initializes a mutex with default propertiespthread_mutex_init(&mtex, &attr)
allows specialized attributesCredit to https://habrahabr.ru/post/277669/ for most of these animations!