Skip to content

Commit

Permalink
replace mutex with tryable spin lock
Browse files Browse the repository at this point in the history
  • Loading branch information
Ubuntu committed Aug 22, 2016
1 parent c7e60c8 commit 639d193
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
25 changes: 25 additions & 0 deletions include/TryableSpinLock.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#ifndef __TRYABLE_SPIN_LOCK_HPP__
#define __TRYABLE_SPIN_LOCK_HPP__

#include <atomic>

// Taken from http://stackoverflow.com/questions/26583433/c11-implementation-of-spinlock-using-atomic
class TryableSpinLock {
std::atomic_flag locked = ATOMIC_FLAG_INIT ;
public:
void lock() {
while (locked.test_and_set(std::memory_order_acquire)) { ; }
}

// from http://stackoverflow.com/questions/19742993/implementing-a-spinlock-in-boost-example-neededhttp://stackoverflow.com/questions/19742993/implementing-a-spinlock-in-boost-example-needed
// is this legit?
bool try_lock() {
return !locked.test_and_set(std::memory_order_acquire);
}

void unlock() {
locked.clear(std::memory_order_release);
}
};

#endif //__TRYABLE_SPIN_LOCK_HPP__
8 changes: 5 additions & 3 deletions src/SalmonUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "SalmonMath.hpp"
#include "SalmonUtils.hpp"
#include "UnpairedRead.hpp"
#include "TryableSpinLock.hpp"

#include "spdlog/fmt/ostr.h"
#include "spdlog/fmt/fmt.h"
Expand Down Expand Up @@ -1799,7 +1800,8 @@ Eigen::VectorXd updateEffectiveLengths(SalmonOpts& sopt, ReadExpT& readExp,
size_t stepSize = static_cast<size_t>(transcripts.size() * 0.1);
size_t nextUpdate{0};

std::mutex updateMutex;
//std::mutex updateMutex;
TryableSpinLock tsl;
/**
* Compute the effective lengths of each transcript (in parallel)
*/
Expand Down Expand Up @@ -1922,7 +1924,7 @@ Eigen::VectorXd updateEffectiveLengths(SalmonOpts& sopt, ReadExpT& readExp,
} // end sequence-specific factor calculation

if (numProcessed > nextUpdate) {
if (updateMutex.try_lock()) {
if (tsl.try_lock()) {
if (numProcessed > nextUpdate) {
sopt.jointLog->info(
"processed bias for {:3.1f}% of the transcripts",
Expand All @@ -1933,7 +1935,7 @@ Eigen::VectorXd updateEffectiveLengths(SalmonOpts& sopt, ReadExpT& readExp,
nextUpdate = numTranscripts - 1;
}
}
updateMutex.unlock();
tsl.unlock();
}
}
++numProcessed;
Expand Down

0 comments on commit 639d193

Please sign in to comment.