【发布时间】: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