Reputation: 1
int total = 200; // total is a global variable
void process()
{
int local;
for( int i = 0 ; i< 100 ; i++ )
{
local = total;
local--;
total = local;
}
}
If 2 threads invoke process()
in parallel, what will be the maximum & minimum value of total after both threads finish processing?
i think the minimum value will be 0 but im not sure. maximum value ?? 199 ?
Upvotes: 0
Views: 201
Reputation: 3968
In C11 this is defined as "undefined behavior," which means that it gives no guarantees about it.
This is more or less true of C99 also, although C99 was not written with concurrency in mind. Each thread is ignorant of the other.
Each thread will look at the global variable 'total' 100 times.
However, each thread gets its own local copy, decrements that, and writes it back to the global variable, total.
However, the thread may take the global variable 'total' and keep a temporary copy, without writing it back until the function ends. In this case the lower bound might be 100.
If they don't keep local copies, total may go down by no more than 1, as they both grab total in synchrony, decrement their local copy, and write back.
Without some way of synchronizing the threads, so that one "grabs" total, modifies it, then "releases" it while the other waits, there's no guarentee it'll reach 0.
Mutexes, semaphores, etc. are ways to syncrhonize access across threads.
Pseudo-code:
process() {
for (loop) {
grab_mutex(total); // Will wait till total is free
total--;
release_mutex(total);
}
}
However, the lower bound is definitely 0; there are no more than 200 opportunities for a decrement.
Upvotes: 1