A
A
Alexander Rakhmaev2019-11-25 17:00:16
C++ / C#
Alexander Rakhmaev, 2019-11-25 17:00:16

Do I need to create a separate function for each thread (_beginthread)?

I want to make two identical calculations in two threads.
I can create a universal function for the thread (Option 1) or it is better to make two separate functions for each thread (Option 2).

Option 1

void Target::threadComputeXCorr(void* pParams)
{
  ArgsXcorrThread * args = (ArgsXcorrThread *)pParams;
  Correlation thisCorrelation = *args->correlation;
  *args->xcorrAnswer = thisCorrelation.xcorr(args->serachArea);
  *args->computeDone = true;
}
int main(){
...
_beginthread(threadComputeXCorr, 0, &argsA0);
_beginthread(threadComputeXCorr, 0, &argsA1);
while ((computeDoneA0 == false) or (computeDoneA1 == false));
...
}


Option 2

void Target::threadComputeXCorr0(void* pParams)
{
  ArgsXcorrThread * args = (ArgsXcorrThread *)pParams;
  Correlation thisCorrelation = *args->correlation;
  *args->xcorrAnswer = thisCorrelation.xcorr(args->serachArea);
  *args->computeDone = true;
}

void Target::threadComputeXCorr1(void* pParams)
{
  ArgsXcorrThread * args = (ArgsXcorrThread *)pParams;
  Correlation thisCorrelation = *args->correlation;
  *args->xcorrAnswer = thisCorrelation.xcorr(args->serachArea);
  *args->computeDone = true;
}
int main(){
...
_beginthread(threadComputeXCorr0, 0, &argsA0);
_beginthread(threadComputeXCorr1, 0, &argsA1);
while ((computeDoneA0 == false) or (computeDoneA1 == false));
...
}


Just for the first option: won't a piece of code with a function actually be executed at the same time? Or will it be copied onto the thread's stack?
(Input-output of data through an argument).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2019-11-25
@rahmaevao

One function can be run in multiple threads.
PS
1. Are you sure you need _beginthread instead of std::thread?
2. Make sure computeDoneA0 and computeDoneA1 are thread safe.
use std::atomic_bool or std::mutex + std::lock_guard to access regular bool

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question