【问题标题】:Issues using multithreading in SFML for C++ [duplicate]在 C++ 的 SFML 中使用多线程的问题 [重复]
【发布时间】: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;
}

Error message

【问题讨论】:

  • 似乎已经解决了这个具体问题,谢谢。

标签: c++ multithreading sfml


【解决方案1】:

必须从主线程进行所有 GUI 更新的情况并不少见。 SFML 很可能甚至不是线程安全的。您需要从其他线程与主线程进行通信,并让它们执行诸如 window.close() 之类的操作。

如果我修改您的示例并简单地从第二个线程返回而不是调用 window.close(),它不会崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多