从在单独线程中运行的单独类访问类实例 [英] accessing a class instance from a separate class running in a separate thread

查看:67
本文介绍了从在单独线程中运行的单独类访问类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含使用它的数据和方法的类。一切都是

完美包含


问题:一个单独的线程必须在当前的这个类的实例中调用一个方法

实例化。这个类只有一个实例化的

,这个外部方法在一个单独的线程中必须访问

它。


我该怎么做?


可能的解决方案:有一个指向更新类的静态指针

指向当前实例化。这个的缺点是,我必须在没有实例化类的时候外部线程没有调用方法。


可能的解决方案#2:使它成为一个静态类,因为在任何给定的时间点,它只有一个实例。这个的缺点,

是每个新实例创建的时候应该清除的数据,而不是担心重置旧数据,我做了

类需要实例化,所以每个实例都有自己的新数据。


你怎么看?

I have a class with data and methods that use it. Everything is
contained perfectly

THE PROBLEM: A separate thread has to call a method in the current
instantiation of this class. There is only ever ONE instantiation of
this class, and this outside method in a separate thread has to access
it.

How do i do this?

POSSIBLE SOLUTION: Have a static pointer to the class that is updated
to point to the current instantiation. The downside to this, is I
must the outside thread is not calling the method when the class is
not instantiated.

POSSIBLE SOLUTION #2: Make it a static class, as there''s only ever
one instance of it at any given point in time. The downside to this,
is the data should be cleared away for when each new instance was
created, and instead of worrying about resetting old data, I made the
class require instantiation so each instance has its own fresh data.

What do you think?

推荐答案

错字:

可能的解决方案:有一个指向更新类的静态指针

to指向当前的实例化。这样做的缺点是,我必须*确保*当类没有实例化时,外部线程没有调用方法


POSSIBLE SOLUTION: Have a static pointer to the class that is updated
to point to the current instantiation. The downside to this, is I
must *ensure* the outside thread is not calling the method when the class is
not instantiated.


- 确保你的类是线程安全的


- 这个类必须实现单例模式(因为那里总是

一个且只有一个例子)


- 单身必须有一个静态方法/属性返回

当前实例(如果不存在则创建它)


- 代码中的任何地方,总是使用此方法/属性访问实例的
。永远不要使用或存储任何变量。


-

OD___
www.e-naxos.com
- make sure your class is thread safe

- this class must implement the singleton pattern (since there''s always
one and only one instance)

- The singleton must have a static method / property returning the
current instance (and create it if none exists)

- Everywhere in your code, always use this method / property to access
the instance. Never use nor store any variable on it.

--
OD___
www.e-naxos.com


您能否向我们提供有关单身模式并且

单身人士?


Titan

Can you point me to more information on "the singleton pattern" and
singletons?

Titan


这篇关于从在单独线程中运行的单独类访问类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆