Skip to content

Commit b2a5c7b

Browse files
committed
Fix thread safety of file reads
1 parent bbbcc56 commit b2a5c7b

File tree

4 files changed

+17
-3
lines changed

4 files changed

+17
-3
lines changed

.github/workflows/rspec.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ jobs:
1111
runs-on: ubuntu-latest
1212
strategy:
1313
matrix:
14-
ruby: [ '2.4', '2.5', '2.6', '2.7' ]
14+
ruby: [ '2.5', '2.6', '2.7' ]
1515

1616
name: Ruby ${{ matrix.ruby }}
1717
steps:

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Useful in cases where:
1212

1313
## Installation
1414

15+
Note: Requires at least ruby 2.5 to support `File#pread` function.
16+
1517
Add this line to your application's Gemfile:
1618

1719
```ruby

lib/wordmap/file_access.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ def read_meta(file, spacer)
6868
def read_at(file, pos, bytes)
6969
# puts "Seeking in #{file.path.split('.wmap', 2)[1][1..-1]} to #{pos}, " \
7070
# "and reading #{bytes} bytes"
71-
file.sysseek(pos)
72-
file.sysread(bytes)
71+
file.pread(bytes, pos)
7372
end
7473
end
7574
end

spec/wordmap_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,19 @@ def reads_breakdown(trace)
112112
expect(wmap['wrong-isbn', trace: trace]).to eq([])
113113
expect(reads_breakdown(trace)).to eq([[:bsearch_vec, 3]])
114114
end
115+
116+
it 'does thread safe lookups' do
117+
wmap['9780385689229'] # Seeking in parent thread.
118+
concurrency = 100
119+
120+
threads = concurrency.times.map {
121+
Thread.new { Thread.current[:book] = !wmap['9780385689229'][0].nil? }
122+
}
123+
124+
success_count = threads.map { |t| t.join[:book] }.count(&:itself)
125+
expect(success_count).to eq(concurrency),
126+
"#{success_count}/#{threads.size} threads succeeded"
127+
end
115128
end
116129

117130
describe '#query' do

0 commit comments

Comments
 (0)