对象的多实例和多线程的线程安全
Thread safety for multiple instance of object and multithreading
我想并行处理这 3 个对象实例中的每一个 运行。我没有全局变量。它是线程安全的吗?或者我需要一些同步机制吗?
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 );
...
}
你能解释一下为什么或为什么不需要同步吗?
编辑:在下面,一些朋友说这个程序无法编译,因为在创建 pthread 时我使用了非静态成员函数调用。我只是想在这里展示我的问题是什么。对于想在 pthreads 中使用非静态成员函数的朋友,这是我的代码;
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);
...
}
Could you explain me why or why not need for syncronization?
有 data race 时需要同步。
由于在您的示例中没有数据,因此不会存在数据竞争。
您可能会发现视频 Plain Threads are the GOTO of todays computing - Hartmut Kaiser - Keynote Meeting C++ 2014 很有启发性。
我想并行处理这 3 个对象实例中的每一个 运行。我没有全局变量。它是线程安全的吗?或者我需要一些同步机制吗?
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 );
...
}
你能解释一下为什么或为什么不需要同步吗?
编辑:在下面,一些朋友说这个程序无法编译,因为在创建 pthread 时我使用了非静态成员函数调用。我只是想在这里展示我的问题是什么。对于想在 pthreads 中使用非静态成员函数的朋友,这是我的代码;
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);
...
}
Could you explain me why or why not need for syncronization?
有 data race 时需要同步。
由于在您的示例中没有数据,因此不会存在数据竞争。
您可能会发现视频 Plain Threads are the GOTO of todays computing - Hartmut Kaiser - Keynote Meeting C++ 2014 很有启发性。