d的GC.free用法效果.
version=FREE;//快些,内存很少
version=COLLECT;//慢,但内存为0
import std.stdio;
import std.datetime.stopwatch;
import core.memory;
immutable int[] intZ = [1,2,3,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23,4,4,6,6,8,8,65,8,23,76,2,57,264,23];
void main() {
writeln(GC.stats);
enum max = 100000;
StopWatch sw;
sw.start();
foreach (i; 0 .. max) {
bool doprint = !(i % (max/10));
int[] z = intZ.dup;
if (doprint) writef("%7d ", GC.stats.usedSize);
version(FREE) GC.free(cast(void*) z.ptr);
version(COLLECT) GC.collect();
if (doprint) writefln("%7d", GC.stats.usedSize);
}
sw.stop();
writefln("Elapsed: %d ms", sw.peek.total!"msecs");
}
超时:
import std.concurrency;
import std.stdio;
import std.exception;
import core.thread;
//
// version = doTimeout;
void compute(int i) {
version (doTimeout) {//注释掉时没问题
writeln("The thread is napping.");
Thread.sleep(2.seconds);
}//未注释超时,则崩溃了.
ownerTid.send(i + 1);
}
void main() {
auto worker = spawn(&compute, 42);
const received = receiveTimeout(
1.seconds,
(int result) {
writefln!"收到: %s"(result);
}
);
enforce(received, "超时");
}
//或者下面
import std.concurrency;
import std.stdio;
import std.exception;
import core.thread;
// Uncomment to see what happens upon time out.
version = doTimeout;
struct Done {
}
void computer() {
bool done = false;
while (!done) {
receive(
(Done _) {
done = true;
},
(int i) {
version (doTimeout) {
writeln("The thread is napping.");
Thread.sleep(2.seconds);
}
ownerTid.send(i + 1);
}
);
}
}
void main() {
// This time we use spawnLinked() so that we will receive
// a LinkTerminated message. And the name is different and
// the argument will be passed later with send().
auto worker = spawnLinked(&computer);
foreach (i; 0 .. 10) {
worker.send(i);
const received = receiveTimeout(
1.seconds,
(int result) {
writefln!"Received the result: %s"(result);
}
);
enforce(received, "Timed out.");
}
// Tell worker to stop.
worker.send(Done());
// Wait for worker to terminate.
receiveOnly!LinkTerminated();
}
浙公网安备 33010602011771号