thread handling c++ linux OS -
i have 3 functions in project written in c++. in same .cpp file , have 2 header files.
now, have 3 corresponding threads that, second thread takes output first thread,and last thread waits until second thread end operations.note threads in "forever loop" i.e. while(1){....}
source.cpp looks this:
#include <iostream> #include "source.h" #include "glob_variables.h" #include "armadillo" #include <vector> using namespace arma; using namespace std; void source::first_function(int size) { for(int i=0;i<size;i++) { container.push_back(i);//container global variable vector of type int declared in glob_variables.h } } //~~~~~~~~~~~~~~~~~~~~~~ void source::second_function() { //sleep until first function fills the vector set set size matrix.n_rows matrix.set_size(container.size(),33); for(int i=0;i<container.size();i++) { for(int j=0;j<50;j++) { matrix(i,j)=i+j;//matrix global variable in glob_variables.h } } } //~~~~~~~~~~~~~~~~~~~~~~ void source::third_function() { //sleep untill second function fills matrix, print cout<<matrix;//print out matrix }
source.h:
#include "glob_variables.h" #include "armadillo" #include <vector> using namespace arma; using namespace std; class source { public: void first_function(int size); void second_function(); void third_function(); };
glob_variables.h:
#include "armadillo" #include <vector> using namespace arma; using namespace std; extern mat matrix; extern vector<int> container;
main.cpp:
#include <iostream> #include <stdio.h> #include <pthread.h> #include "source.h" #include "glob_variables.h" #include "armadillo" #include <vector> using namespace arma; using namespace std; //thread functions void* first_reader(void* id1) { source mysource; while(1) { mysource.first_function(80); } } void* second_reader(void* id2) { source mysource; while(1) { mysource.second_function(); } } void* third_reader(void* id3) { source mysource; while(1) { mysource.third_function(); } } int main() { pthread_t first; pthread_t second; pthread_t third; int hndl_first; int hndl_second; int hndl_third; hndl_first = pthread_create(&first, null, first_reader, null); hndl_second= pthread_create(&second, null, second_thread, null); hndl_third;= pthread_create(&third, null,third_thread, null); pthread_exit(null); return 0; }
can have techniques this, or simple example. thanks.
try using following link. autoresetevent fulfills requirement. code in link expect.
Comments
Post a Comment