In this part you will solve the concurrent access problem from Exercise 1, such that the final result is always zero. You can choose to either use the provided starter code or to copy your solution to Exercise 1 into the suitable directories. In the go-channel part you will probably wish to use the provided starter code as no equivalent exists in Exercise 1.
In your solution, make sure that the two threads intermingle. Running them one after the other would somewhat defeat the purpose. It may be useful to change the number of iterations in one of the threads, such that the expected final result is not zero (say, -1). This way it is easier to see that your solution actually works, and isn't just printing the initial value.
- POSIX has both mutexes (
pthread_mutex_t
) and semaphores (sem_t
). Which one should you use? - Acquire the lock, do your work in the critical section, and release the lock
Using shared variable synchronization is not the idiomatic go. You should instead create a server that select{}
s transformations to its own data. Have two other goroutines tell the server to increment & decrement its local variable. Note that this variable will no longer be global, so it cannot be read by other goroutines. The proper way to handle this is to create another select{}
-case where others can request a copy of the value.
Before attempting to do the exercise, have a look at the following chapters of the interactive go tutorial:
Remember from Exercise 1 where we had no good way of waiting for a goroutine to finish? Try sending a "finished"/"worker done" message on a separate channel. If you use different channels for the two threads, you will have to use select { case... }
so that it doesn't matter what order they arrive in.
In the theory part you listed some advantages with message passing and shared variable synchronization. Do you still agree with what you answered?
Python provides both Locks (which are like mutexes) and Queues (which are kind of like channels). Solve the problem in whatever way you believe to be the simplest.