Reputation: 47
I want to each of these 3 object instance run in parallel. I have no global variables. Is it thread-safe? or do i need some syncronization mechanism?
class myClass{
public:
myClass();
~myClass();
void myFunction();
}
int main() {
myClass myObj1, myObj2, myObj3;
pthread_t myThread1, myThread2, myThread3;
pthread_create(&myThread1, NULL, myObj1::myFunction, NULL );
pthread_create(&myThread2, NULL, myObj2::myFunction, NULL );
pthread_create(&myThread3, NULL, myObj3::myFunction, NULL );
...
}
Could you explain me why or why not need for syncronization?
EDIT: In the below, some friends say that this program cannot compile because while creating pthread i used non-static member function call. I just wanted to show what is my problem here. For Friends who want to use non-static member function with pthreads, its my code;
struct thread_args{
myClass* itsInctance;
//int i,j,k; // also if you want to pass parameter to function you use in
//pthread_create u can add them here
}
void* myThread(void* args){
thread_args *itsArgs = (thread_args*)args;
itsArgs->itsInstance->myFunciton();
}
int main() {
myClass myObj1;
pthread_t myThread1;
thread_args itsArgs;
itsArgs.itsInstance = &myObj1;
// also if you have any other params, fill them here
pthread_create(&myThread1, NULL, myThread, &itsArgs);
...
}
Upvotes: 1
Views: 281
Reputation: 136515
Could you explain me why or why not need for syncronization?
You need synchronization when there is a data race.
Since in your example there is no data, there cannot be a data race.
You may find video Plain Threads are the GOTO of todays computing - Hartmut Kaiser - Keynote Meeting C++ 2014 instructive.
Upvotes: 1