I am working on a homework assignment and I've hit a wall. The assignment is to use 2 threads with controlling mutex to reduce a number x over a loop of 5 iterations.
The first thread does x=x-5
The second thread does x = x/5
The proper result should reduce x to 5 from 19530 over 5 iterations alternating between thread1 and thread2 at each iteration.
I have the following result as of now:
Thread1: x = 19525
Thread1: x = 19520
Thread1: x = 19515
Thread1: x = 19510
Thread1: x = 19505
From above it is clear that my second thread is not only not doing it's job but it's not doing anything at all.
Below is my code, it is written in C++ but the style is using the tools we learned in class which is how one would do it in C but it should work the same either way.
#include<iostream> #include <stdio.h> #include <stdlib.h> #include <pthread.h> using namespace std; void *first(void *); void *second(void *); pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; int x = 19530; // global var that is being manipulated int i = 1; // counter for the loops int main() { int t1, t2; pthread_t thread1, thread2; if((t1 = pthread_create( &thread1, NULL, first, NULL))) { printf("Thread creation failed: %d\n", t2); } if((t2 = pthread_create( &thread2, NULL, second, NULL))) { printf("Thread creation failed: %d\n", t2); } pthread_join(thread1, NULL); pthread_join(thread2, NULL); return(0); } void *first(void *){ // function for thread1 for(; i <=5; i++){ pthread_mutex_lock(&mymutex); x = x-5; cout << "Thread1: x = " << x << endl; pthread_mutex_unlock(&mymutex); } } void *second(void *){ // function for thread2 for(; i<=5; i++){ pthread_mutex_lock(&mymutex); x = x/5; cout << "Thread2: x = " << x << endl; pthread_mutex_unlock(&mymutex); } } Note I am brand new to the concept threads and mutex. And I'd prefer to stick to the way I have learned in class which I believe is called "the C way".
thread1 unlocks thread2 and viceversa?Yes, each thread would have a mutex that it wait for, update x, then unlock the other thread's mutex, then loop back and wait for it's mutex to get unlocked.