我的问题,如上所述,显而易见,我将详细描述该方案。 有一个名为单用Singleton模式实现为下面的类,在文件singleton.h:在Linux上的共享库上存在多个单例实例
/*
* singleton.h
*
* Created on: 2011-12-24
* Author: bourneli
*/
#ifndef SINGLETON_H_
#define SINGLETON_H_
class singleton
{
private:
singleton() {num = -1;}
static singleton* pInstance;
public:
static singleton& instance()
{
if (NULL == pInstance)
{
pInstance = new singleton();
}
return *pInstance;
}
public:
int num;
};
singleton* singleton::pInstance = NULL;
#endif /* SINGLETON_H_ */
然后,有一个叫HELLO.CPP插件如下:
#include <iostream>
#include "singleton.h"
extern "C" void hello() {
std::cout << "singleton.num in hello.so : " << singleton::instance().num << std::endl;
++singleton::instance().num;
std::cout << "singleton.num in hello.so after ++ : " << singleton::instance().num << std::endl;
}
你可以看到该插件调用单例并更改单例中的属性num。
最后,还有一个主要功能使用Singleton和插件如下:
#include <iostream>
#include <dlfcn.h>
#include "singleton.h"
int main() {
using std::cout;
using std::cerr;
using std::endl;
singleton::instance().num = 100; // call singleton
cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton
// open the library
void* handle = dlopen("./hello.so", RTLD_LAZY);
if (!handle) {
cerr << "Cannot open library: " << dlerror() << '\n';
return 1;
}
// load the symbol
typedef void (*hello_t)();
// reset errors
dlerror();
hello_t hello = (hello_t) dlsym(handle, "hello");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol 'hello': " << dlerror() << '\n';
dlclose(handle);
return 1;
}
hello(); // call plugin function hello
cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton
dlclose(handle);
}
和生成文件的以下内容:
example1: main.cpp hello.so
$(CXX) $(CXXFLAGS) -o example1 main.cpp -ldl
hello.so: hello.cpp
$(CXX) $(CXXFLAGS) -shared -o hello.so hello.cpp
clean:
rm -f example1 hello.so
.PHONY: clean
那么,什么是输出? 我认为有以下几点:
singleton.num in main : 100
singleton.num in hello.so : 100
singleton.num in hello.so after ++ : 101
singleton.num in main : 101
然而,实际的输出如下:
singleton.num in main : 100
singleton.num in hello.so : -1
singleton.num in hello.so after ++ : 0
singleton.num in main : 100
事实证明,有单件类的两个实例。
为什么?
你想让这个singleton成为你正在执行的一个进程的单例吗?还是一个违反所有受保护内存的“全系统”单身人士为我们提供的? – sarnold 2011-12-24 09:06:44
除非明确说明,否则问题通常不是很明显。你想共享库共享单例吗?你理论中的任何一种行为还是实际体验它?没有办法知道,除非你告诉我们。 – 9000 2011-12-24 09:07:19
@sarnold:有一个众所周知的全系统单例模式,不受地址空间限制:它被称为服务器。但直到原始海报告诉他的代码的_purpose_,很难说这个模式是否合适。 – 9000 2011-12-24 09:12:11