相关疑难解决方法(0)

浮点数学是否破碎?

请考虑以下代码:

0.1 + 0.2 == 0.3  ->  false
Run Code Online (Sandbox Code Playgroud)
0.1 + 0.2         ->  0.30000000000000004
Run Code Online (Sandbox Code Playgroud)

为什么会出现这些不准确之处?

language-agnostic math floating-point floating-accuracy

2798
推荐指数
28
解决办法
28万
查看次数

C++中的条件变量wait_for

我正在使用condition_variableVisual Studio 2019。该condition_variable.wait_for()函数在std::cv_status::no_timeout没有任何通知的情况下返回。

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

std::condition_variable cv;
std::mutex mtx;
bool called = false;

void printThread()
{
    std::unique_lock<std::mutex> lck(mtx);
    while (std::cv_status::timeout == cv.wait_for(lck, std::chrono::seconds(1)))
    {
        std::cout << "*";
    }
    std::cout << "thread exits" << std::endl;
}

int main()
{
    std::thread th(printThread);
    th.join();
    std::cout << "program exits" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我认为代码永远不会退出并继续打印*,但在打印一些*.

这是输出:

********************************************************************thread exits
program exits
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?难道就是所谓的“虚假唤醒”?

c++ condition-variable unique-lock

10
推荐指数
1
解决办法
1405
查看次数

为什么Thread.Sleep在运行其他应用程序时等待的时间比请求的长?

关于C#中的线程,我有一个小问题.出于某种原因,当我打开Chrome时,我的线程从32ms延迟加速到16ms延迟,当我关闭Chrome时它会回到32ms.我正在使用Thread.Sleep(1000 / 60)延迟.有人可以解释为什么会发生这种情况,并建议一个可能的解决方案吗?

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading;

 namespace ConsoleApplication2
 {
     class Program
     {
         static bool alive;
         static Thread thread;
         static DateTime last;

         static void Main(string[] args)
         {
             alive = true;
             thread = new Thread(new ThreadStart(Loop));
             thread.Start();

             Console.ReadKey();
         }

         static void Loop()
         {
             last = DateTime.Now;

             while (alive)
             {
                 DateTime current = DateTime.Now;
                 TimeSpan span = current - last;
                 last = current;

                 Console.WriteLine("{0}ms", span.Milliseconds);
                 Thread.Sleep(1000 / 60);
             }
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading behavior

4
推荐指数
2
解决办法
1446
查看次数