Skip to content
This repository has been archived by the owner on May 26, 2022. It is now read-only.

fix: add read/write locks #85

Merged
merged 1 commit into from Apr 22, 2020
Merged

fix: add read/write locks #85

merged 1 commit into from Apr 22, 2020

Conversation

Stebalien
Copy link
Member

We keep running into races so I figured we might as well just make this all thread-safe. It should have no effect on performance.

The actual bug was setting the write deadline while writing. But we might as well just have read and write locks.

fixes https://github.com/libp2p/go-libp2p-swarm/issues/205

We keep running into races so I figured we might as well just make this all
thread-safe. It should have no effect on performance.

The actual _bug_ was setting the write deadline while writing. But we might as
well just have read and write locks.

fixes https://github.com/libp2p/go-libp2p-swarm/issues/205
@Stebalien Stebalien merged commit 2c77fd7 into master Apr 22, 2020
@Stebalien Stebalien deleted the fix/deadline-race branch April 22, 2020 16:40
// deadline.

c.writeLock.Lock()
defer c.writeLock.Unlock()
Copy link

@0xKiwi 0xKiwi May 14, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend unifying these into a sync.RWMutex and use lock.RLock() in combination with lock.Lock(). Since the write lock is set without setting the read lock.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're locking reads independently from writes. The underlying library does not allow concurrent reads from multiple threads or concurrent writes from multiple threads.

However, reading while writing (as long as only one thread is reading reading and only one thread is writing) is perfectly fine. As a matter of fact, that's how we normally use connections.

Note: the specific bug we were fixing here was concurrently setting a deadline while writing. We could have simply locked the write side and that's it, but we've run into hard to track down race conditions in the past where we were reading from multiple threads without synchronizing (usually in error paths where we're throwing away the connection anyways).

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it! Thank you for the explanation!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants