- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
The questions are limited to X86/LINUX environment.
1. One thread write a var with a lock,other threads read this var without lock. When the write thread unlocked,Could other threads read the new value immediately?
[cpp] volatile int a=0;
/* thread 1(write) */
lock();
a = 10;
unlock();
/* thread 2(read) */
printf("%d",a);[/cpp]
2. One thread read a var with a lock,another thread write this var without lock. When the read thread read after write complete,Could it read the new value immediately?
[cpp] volatile int a=0;
/* thread 1(read) */
lock();
printf("%d",a);
unlock();
/* thread 2(write) */
a = 10; [/cpp]
Link Copied
2 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Quoting Ma Bo
The questions are limited to X86/LINUX environment.
1. One thread write a var with a lock,other threads read this var without lock. When the write thread unlocked, Could other threads read the new value immediately?
...
Yes, as soon as the system scheduler givesother threads execution control.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
The reading thread does not necessarily require the lock to read the updated variable.
You would use a lock in cases where the writing thread(s) update multiple variables and where the read requires to read the complete set of updates (without partial interviening updates). You may need the read lock in cases of dependency (e.g. traversing a linked list where nodes can be removed and/or added).
If your shared variable is not volatile then you may require a memory barrier/fence.
Jim Dempsey
You would use a lock in cases where the writing thread(s) update multiple variables and where the read requires to read the complete set of updates (without partial interviening updates). You may need the read lock in cases of dependency (e.g. traversing a linked list where nodes can be removed and/or added).
If your shared variable is not volatile then you may require a memory barrier/fence.
Jim Dempsey

Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page