gpt4 book ai didi

c# - Thread.Sleep(0) 没有按描述工作?

转载 作者:可可西里 更新时间:2023-11-01 09:14:23 26 4
gpt4 key购买 nike

我正在阅读 this excellent article关于线程并阅读以下文本:

Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

我想测试一下,下面是我的测试代码:

static string s = "";

static void Main(string[] args)
{
//Create two threads that append string s
Thread threadPoints = new Thread(SetPoints);
Thread threadNewLines = new Thread(SetNewLines);

//Start threads
threadPoints.Start();
threadNewLines.Start();

//Wait one second for threads to manipulate string s
Thread.Sleep(1000);

//Threads have an infinite loop so we have to close them forcefully.
threadPoints.Abort();
threadNewLines.Abort();

//Print string s and wait for user-input
Console.WriteLine(s);
Console.ReadKey();
}

threadPoints 和 threadNewLines 运行的函数:

static void SetPoints()
{
while(true)
{
s += ".";
}
}

static void SetNewLines()
{
while(true)
{
s += "\n";
Thread.Sleep(0);
}
}

如果我正确理解 Thread.Sleep(0),输出应该是这样的:

............        |
.............. |
................ | <- End of console
.......... |
............. |
............... |

但我得到这个作为输出:

....................|
....................|
.... |
|
|
....................|
....................|
................. |
|

鉴于帖子开头提到的文章被许多程序员强烈推荐,我只能假设我对 Thread.Sleep(0) 的理解是错误的。因此,如果有人可以澄清,我将不胜感激。

最佳答案

什么thread.sleep(0) 是为了释放cpu 来处理其他线程,但这并不意味着另一个线程不能成为当前线程。如果您尝试将上下文发送到另一个线程,请尝试使用某种信号。

关于c# - Thread.Sleep(0) 没有按描述工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com