【发布时间】:2009-08-05 15:21:31
【问题描述】:
跟进问题: This question
如链接问题中所述,我们有一个 API,它使用轮询 select() 的事件外观来处理用户定义的回调。
我有一个这样的课程:
class example{
public:
example(){
Timer* theTimer1 = Timer::Event::create(timeInterval,&example::FunctionName);
Timer* theTimer2 = Timer::Event::create(timeInterval,&example::FunctionName);
start();
cout<<pthread_self()<<endl;
}
private:
void start(){
while(true){
if(condition)
FunctionName();
sleep(1);
}
}
void FunctionName(){
cout<<pthread_self()<<endl;
//Do stuff
}
};
这背后的想法是,如果条件为真或计时器到时,您希望 FunctionName 被调用。不是一个复杂的概念。我想知道的是,是否会在 start() 函数和回调中同时调用 FunctionName ?这可能会对我造成一些内存损坏,因为它们访问的是非线程安全的共享内存。
我的测试告诉我,它们确实在不同的线程中运行(仅当我使用事件时才会损坏),即使:cout<<pthread_self()<<endl; 表示它们具有相同的线程 ID。
有人可以向我解释这些回调是如何分叉的吗?他们执行的顺序是什么?他们在什么线程中运行?我假设它们在执行 select() 的线程中运行,但是它们何时获得相同的线程 ID?
【问题讨论】:
-
应标记为 C 而不是 C++
-
@Tom,代码示例明显是C++...