【发布时间】:2011-05-31 07:36:19
【问题描述】:
我已经在 C# 中声明了一个 static public int 然后该 int 被提供给它的构造函数中的一个线程,线程的工作很容易增加它,但它不会发生 这里我声明了静态值:
class Global
{
static public int hardcap = 100;
public int speed;
static public Semaphore myhitpoints = new Semaphore(1, 1);
static public Semaphore oponenthitpoints = new Semaphore(1, 1);
static public int mhp = 100;
static public int ohp = 100;
static public int mmana = 0;
static public int omana = 0;
public static Charm dragonblade = new Charm(10, 30, 3, myhitpoints, oponenthitpoints, mhp, ohp, "dragon blade", mmana);
public static Charm dragonshield = new Charm(30, 10, 5, myhitpoints, oponenthitpoints, mhp, ohp, "dragon shield", mmana);
public static Charm b1charm;
public static Charm b2charm;
public static Opponent enemy;
}
class ManaWell
{
int mana_regen;
int cap = 1000;
int target;
public ManaWell(int x, int y)
{
mana_regen = x;
target = y;
}
public void Refill()
{
while (true)
{
// if (this.target + mana_regen <= cap)
if (target+mana_regen<cap)
{
Thread.Sleep(3000);
target += mana_regen;
MessageBox.Show(target.ToString());
}
}
}
}
ManaWell mw1 = new ManaWell(20,Global.mmana);
ManaWell mw2 = new ManaWell(20,Global.omana);
Thread tmw1 = new Thread(new ThreadStart(mw1.Refill));
Thread tmw2 = new Thread(new ThreadStart(mw2.Refill));
tmw1.Start();
tmw2.Start();
所以目标工作正常,但 y 不会增加。
【问题讨论】:
-
您的代码不符合您的问题。
-
您没有显示任何个静态变量。请给出一个简短但完整的例子来说明你正在尝试做什么。
-
我的印象是你完全在滥用线程。您不想让游戏中的每个对象都有自己的线程。通常你在游戏模拟中只使用一个线程(除了一些选择问题,比如路径/碰撞)
-
在使用多线程时,您可能会犯很多错误。指令重排序(内存屏障,内存模型,获取/释放语义,易失性),锁定(死锁,锁层次结构,隐藏锁,如事件循环,...),性能(线程切换成本,锁争用,1MB 地址空间保留给每个线程的堆栈,...)要知道的东西太多了,很容易出错。如果你真的决定走这条路,你的程序会很慢,吃很多内存(在 32 位进程中,你会得到一个非常低的对象限制),很难调试,我敢打赌你会遇到一些不确定的错误.
标签: c# static multithreading