I have a certain resource and two threads one is producer and the other one is consumer. The producer update the resource every time interval and the update takes some time and I don't want the consumer to wait. I want his instead to work with the old values of the resource while the producer update. How do I synchronize the two threads without putting the consumer to wait
Asked
Active
Viewed 113 times
0
-
1What's making you wait now? – Carl Norum Jun 23 '13 at 15:48
-
1POSIX thread mutex and the try-lock function? See e.g. [this old question](http://stackoverflow.com/questions/9258308/how-to-use-pthread-mutex-trylock) and its answers. Then the consumer tries to poll the resource at regular intervals, and if it fails to lock the mutex goes on as if nothing happened. – Some programmer dude Jun 23 '13 at 15:51
-
Is the question somehow related to spinlock? – Recker Jun 23 '13 at 15:52
-
Depends on your setup. Can you create a new resource and copy it over when you're done? If not, we'll need to know more about the setup – Kevin Jun 23 '13 at 16:54
2 Answers
2
You can have an atomic pointer through which the consumer reads what the producer produced. Once the producer generated new data, change the value of the atomic pointer to point to that new data instead.

Maxim Egorushkin
- 131,725
- 17
- 180
- 271
0
The shared resource is going to have to be locked while it's being updated/read from. I guess the consumer could copy the resource into a buffer of its own? Or would that take just as long?

Imre Kerr
- 2,388
- 14
- 34