【发布时间】:2021-09-03 16:13:00
【问题描述】:
我正在尝试在使用 SFML 游戏库时创建一个单独的线程。这是一个非常简单的例子。
我正在使用 WSL 和 libsfml-dev 库。我的问题是,我似乎无法在主线程以外的线程上使用 SFML 库执行某些操作。例如,在下面的代码中,如果单击转义,则会出现错误。应该发生的是程序在循环条件失败时简单地退出。
如果你想自己运行代码...
获取库:apt-get install libsfml-dev
g++ 编译器参数:g++ test.cpp -pthread -lsfml-graphics -lsfml-window -lsfml-system
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
// Create window object
sf::RenderWindow window(sf::VideoMode(800, 800), "");
using namespace std;
void *func(void *threadid) {
// Show thread was created
cout << "New thread was ran." << endl;
while (window.isOpen()) {
// This action kills the program and not in a nice way
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
window.close();
}
}
pthread_exit(NULL);
}
int main() {
// Create new thread
pthread_t threads[1];
int val;
val = pthread_create(&threads[0], NULL, func, (void *)1);
cout << "Main thread was ran." << endl;
// This is here so that the program doesn't exit
while (window.isOpen()) {}
return 0;
}
【问题讨论】:
-
似乎已经解决了这个具体问题,谢谢。
标签: c++ multithreading sfml