thread writing value.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <pthread.h>
int counter = 10;
void *worker(void *arg)
{
    counter--;
    return = 0;
}
int main()
{
    pthread_t p1 = 0;
    pthread_t p2 = 0;
    pthread_create(&p1, 0, worker, 0);
    pthread_create(&p2, 0, worker, 0);
    pthread_join(p1);
    pthread_join(p2);
}

counter possible value will be 7,8,9,10.

Thread 1 will write 9(1001) back.
The original value is 10(1010).
1001
1010
The immediate value for thread 2 to read:
1000 8
1001 9
1010 10
1011 11
so: 7 8 9 10



Last edited on
Consider using std::thread. See:

http://www.cplusplus.com/reference/thread/thread/?kw=thread

Do you have any questions?
> counter possible value will be 7,8,9,10.
1. Your counter counts down, not up.
2. It doesn't compile anyway.
3. It doesn't work as you describe, even if it compiled and you had ++ instead of --.

> counter--;
Consider that this has to compile to something like
load reg,counter
dec reg
store reg,counter

You have NO guarantee that p1 won't get scheduled out at the point of "dec reg" before p2 comes along and does it's thing, and then p1 resumes.

The result of this little race condition is that counter is only decremented once rather than twice.
Topic archived. No new replies allowed.