I'm new to multithreading in C , and I am not sure how to apply it. Can anyone help?
I'm trying to make the BinomialTree
function multithreaded,
This is what I have tried so far:
thread th1(BinomialTree,S0, r, q, sigma, T, N);
th1.join();
But it doesn't work
int main() {
double K = 100;
double S0 = 100;
double r = 0.03;
double q = 0;
double sigma = 0.3;
double T = 1;
const int N = 1000;
shared_ptr<Payoff> callPayOff = make_shared<PayoffCall>(K, r, T);
EuropeanOption europeanCall(T, callPayOff);
BinomialTree tree(S0, r, q, sigma, T, N);
double callPrice1 = tree.Price(europeanCall);
}
CodePudding user response:
From
BinomialTree tree(S0, r, q, sigma, T, N);
double callPrice1 = tree.Price(europeanCall);
it looks like BinomialTree tree(...)
is the definition of an object, and tree.Price
is the actual function call. Your thread probably should be running the &BinomialTree::Price
function.
That said,
thread th1(&BinomialTree::Price, tree, 0, r, q, sigma, T, N);
th1.join();
will just cause the main thread to wait while th1
is running. For multi-threading, you want to do something useful with multiple threads at the same time. And in this simple example, there's of course nothing obvious that you can do. But in your real program, you might want to have a look.
Note: since you've left out the code of &BinomialTree::Price
, we can't tell if you could use multiple threads inside that function.
CodePudding user response:
If you have a divide-and-conquer algorithm like q-sort, you can break data-set into smaller data-sets, each of those datasets become independent problems that can be processed in parallel and then combined when done. This will work well for trees that do not cross link but the binomial tree mentioned does have cross-links so might be more difficult to do. There is no silver bullet though, you can only parallelize if the algorithm allows you to.