Obj-C performSelector OnThread in pthread C++
Obj-C performSelector OnThread in pthread C++
我有一个关于c++ pthread的问题。
如果我有一个Thread1和Thread2。
是否有一种方法可以在Thread2上执行从Thread1调用的Thread2方法?
//code example
//we can suppose that Thread2 call has a method
void myThread2Method();
//I would to call this method from Thread1 but your execution must to run on Thread2..
thread1.myThread2Method()
我想知道是否存在类似于Obj-c中存在的performSelector OnThread的方式。
对于纯pthread没有类似的方法。这个(你提到的objective-C函数)只适用于有运行循环的线程,所以它仅限于objective-C。
在pure-c中没有等价的运行循环/消息泵,这些依赖于gui(例如iOS等)。
唯一的选择是让线程2检查某种条件,如果设置了,则执行预定义的任务。(这可能是一个全局函数指针,如果指针不为空,线程2会定期检查并执行函数)。
下面是一个粗略的示例,展示了基本的工作原理
void (*theTaskFunc)(void); // global pointer to a function
void pthread2()
{
while (some condition) {
// performs some work
// periodically checks if there is something to do
if (theTaskFunc!=NULL) {
theTaskFunc(); // call the function in the pointer
theTaskFunc= NULL; // reset the pointer until thread 1 sets it again
}
}
...
}
void pthread1()
{
// at some point tell thread2 to exec the task.
theTaskFunc= myThread2Method; // assign function pointer
}
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 直接读取 pthread 互斥锁的所有者字段是否安全?
- 为什么 pthread 会减慢代码速度?
- 对 pthread CLion 的未定义引用
- C++ 17:pthread的生成文件标志
- 将带有结构的参数传递给 pthread
- Posix 线程类和启动例程 (pthread)
- 在 pthread 中使用共享变量