【问题标题】:not working threads in sfmlsfml 中的线程不工作
【发布时间】:2019-01-01 14:57:27
【问题描述】:

您好,开始我想说我是这方面的新手,很抱歉这个基本问题。

#include <SFML/System.hpp>
#include <iostream>

void func()
{
    // this function is started when thread.launch() is called

    for (int i = 0; i < 10; ++i)
        std::cout << "I'm thread number one" << std::endl;
}

int main()
{
    // create a thread with func() as entry point
    sf::Thread thread(&func);

    // run it
    thread.launch();

    // the main thread continues to run...

    for (int i = 0; i < 10; ++i)
        std::cout << "I'm the main thread" << std::endl;

    return 0;
}

这是来自 sfml 官方网站的代码,它应该正在打印:

我是第一个线程

我是主线

我是主线

我是第一个线程

我是第一个线程

等,但控制台打印第一个 10 倍“我是第一个线程”和第二个,我不知道为什么。我用这个教程安装了sfml https://youtu.be/axIgxBQVBg0 .

【问题讨论】:

  • 您无法控制线程、它们何时真正开始运行以及运行多长时间。尝试增加写入输出的次数,您应该会看到每个线程混合的 blocks 输出(如果没有同步,输出不会来自每个输出)。
  • 操作系统决定何时调度线程。如果您想要可预测的多线程行为,则需要同步原语。如果您继续阅读,我假设您正在关注的教程有一个带有互斥锁的示例。此外,SFML 明确建议使用 std::thread 而不是 sf::Thread

标签: c++ multithreading visual-studio sfml


【解决方案1】:

SFML 网站上的示例是潜在 输出的示例。如果您注意到该示例中给出的输出似乎有点不可预测,那是因为它是。你极不可能复制它。作为noted in the comments,如果没有进一步的同步,您将无法显式控制线程。

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2013-10-04
    相关资源
    最近更新 更多