how to multithread using c++
Hi,
I need to implement a timer associated with a state[in a state
machine].In case the statemachine does not get any input for a
particular period of time, the timer should reset and there should be
default action.
How do I implement multiple threads in c++[in linux].
I got this example on the web .its uses 2 threads.but it does not
execute together.
thread 1 executes then thread 2
void *task1(void *X);
void *task2(void *X);
int main(int argc, char *argv[])
{
pthread_t ThreadA,ThreadB;
int N;
if(argc != 2){
std::cout << "error" <<"\n";
exit (1);
}
N = atoi(argv[1]);
pthread_create(&ThreadA,NULL,task1,&N);
pthread_create(&ThreadB,NULL,task2,&N);
std::cout << "waiting for threads to join" <<"\n";
pthread_join(ThreadA,NULL);
pthread_join(ThreadB,NULL);
return(0);
}
void *task1(void *X)
{
int *Temp;
Temp = static_cast<int *>(X);
for(int Count = 1;Count < *Temp;Count++){
std::cout << "work from thread A: " << Count << " * 2 = "
<< Count * 2 <<"\n";
}
std::cout << "Thread A complete" <<"\n";
}
void *task2(void *X)
{
int *Temp;
Temp = static_cast<int *>(X);
for(int Count = 1;Count < *Temp;Count++){
std::cout << "work from thread B: " << Count << " + 2 = "
<< Count + 2 <<"\n";
}
std::cout << "Thread B complete" << "\n";
}