github.com/avahowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/modules/miner/cpuminer.go (about)

     1  package miner
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  // threadedMine starts a gothread that does CPU mining. threadedMine is the
     8  // only function that should be setting the mining flag to true.
     9  func (m *Miner) threadedMine() {
    10  	// There should not be another thread mining, and mining should be enabled.
    11  	m.mu.Lock()
    12  	if m.mining || !m.miningOn {
    13  		m.mu.Unlock()
    14  		return
    15  	}
    16  	m.mining = true
    17  	m.mu.Unlock()
    18  
    19  	// Solve blocks repeatedly, keeping track of how fast hashing is
    20  	// occurring.
    21  	cycleStart := time.Now()
    22  	for {
    23  		// Kill the thread if mining has been turned off.
    24  		m.mu.Lock()
    25  		if !m.miningOn {
    26  			m.mining = false
    27  			m.mu.Unlock()
    28  			return
    29  		}
    30  		bfw := m.blockForWork()
    31  		target := m.persist.Target
    32  		m.mu.Unlock()
    33  
    34  		// Grab a block and try to solve it.
    35  		b, solved := m.SolveBlock(bfw, target)
    36  		if solved {
    37  			err := m.managedSubmitBlock(b)
    38  			if err != nil {
    39  				m.log.Println("ERROR: An error occurred while cpu mining:", err)
    40  			}
    41  		}
    42  
    43  		// Update the hashrate. If the block was solved, the full set of
    44  		// iterations was not completed, so the hashrate should not be updated.
    45  		m.mu.Lock()
    46  		if !solved {
    47  			nanosecondsElapsed := 1 + time.Since(cycleStart).Nanoseconds() // Add 1 to prevent divide by zero errors.
    48  			cycleStart = time.Now()                                        // Reset the cycle counter as soon as the previous value is measured.
    49  			m.hashRate = 1e9 * solveAttempts / nanosecondsElapsed
    50  		}
    51  		m.mu.Unlock()
    52  	}
    53  }
    54  
    55  // CPUHashrate returns an estimated cpu hashrate.
    56  func (m *Miner) CPUHashrate() int {
    57  	m.mu.Lock()
    58  	defer m.mu.Unlock()
    59  	return int(m.hashRate)
    60  }
    61  
    62  // CPUMining indicates whether the cpu miner is running.
    63  func (m *Miner) CPUMining() bool {
    64  	m.mu.Lock()
    65  	defer m.mu.Unlock()
    66  	return m.miningOn
    67  }
    68  
    69  // StartCPUMining will start a single threaded cpu miner. If the miner is
    70  // already running, nothing will happen.
    71  func (m *Miner) StartCPUMining() {
    72  	m.mu.Lock()
    73  	defer m.mu.Unlock()
    74  	m.miningOn = true
    75  	go m.threadedMine()
    76  }
    77  
    78  // StopCPUMining will stop the cpu miner. If the cpu miner is already stopped,
    79  // nothing will happen.
    80  func (m *Miner) StopCPUMining() {
    81  	m.mu.Lock()
    82  	defer m.mu.Unlock()
    83  	m.hashRate = 0
    84  	m.miningOn = false
    85  }