Understanding Multi-threading (boost) in bitcoin initialization

1

1

I am not familiar with boost in c++. Can any expert please explain in simple terms what is happening in the below code ? Is it like the logic in ThreadScriptCheck is scheduled to be run in background or how?

This is taken from bitcoin initialization (src/init.cpp). The classes are defined in src/scheduler.h

AppInit2():

// Assume value of nScriptCheckThreads is 4

if (nScriptCheckThreads) {
    for (int i=0; i<nScriptCheckThreads-1; i++)
        threadGroup.create_thread(&ThreadScriptCheck);
}

// Start the lightweight task scheduler thread
CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));

Paarth

Posted 2015-12-23T12:15:14.603

Reputation: 105

Answers

2

The boost::thread_group class doesn't do very much. It's basically just a container of threads. It doesn't really have any scheduling or dispatch functions. That this thread is part of a thread group doesn't really matter.

The CScheduler code allows a thread to run a task at a particular time. It requires a thread to run the various tasks that it schedules. This code creates a thread to runs those tasks for this CScheduler and adds it to the thread group.

David Schwartz

Posted 2015-12-23T12:15:14.603

Reputation: 46 931

Thank you so much for your explanation. Also, can you point me out what those tasks (being run in CScheduler) exactly are? The LogPrintf above this code snippet in src/init.cpp mentions that it runs script verification, but I am unable to find relevant logic in the source code.Paarth 2015-12-24T03:53:19.950

Also, GenerateBitcoins in sec/miner.cpp also creates a threadgroup with which it associates the BitcoinMiner. As per what I understand from your explanation, that this is just associating the thread in a group. But then how is the miner run in background?Paarth 2015-12-24T05:43:09.270

The bitcoin daemon no longer runs a miner in the background, or at all for that matter. The scheduler is used for periodic tasks such as making outbound connections.David Schwartz 2015-12-24T05:46:22.413

But where is the scheduler for BitcoinMiner ? There is no scheduler logic used for running the thread group associated with mining. miner.cpp has logic only for thread group creation.Paarth 2015-12-26T10:01:19.630