pthread 比没有线程慢

Céd*_*ond 1 c++ multithreading pthreads thread-safety

你好,我试图在我的塔防中添加线程以使其更快,但现在速度变慢了。

代码结构非常简单

主要以 sdl opengl init 和 init 一切开始。然后游戏循环。无线程顺序: 1:keyboard and mouse event first 2:gameManager 3:drawGlScene

游戏管理器计算一切:移动怪物,攻击怪物,创建攻击动画和声音,检查你是赢了还是输了,如果波完成了,怪物产生,如果速度模式打开,这个功能会运行2次。和其他一些小功能。

绘图功能使用所有数据来绘制所有内容。使用绘图功能有 0 个数据修改

我使用的 cpu 是四核,这里是主要的可视化部分第一步初始化线程的东西

int main ( int argc, char** argv )
{
 pthread_t t_engine;
 pthread_attr_t attr;
 pthread_attr_init(&attr);
 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
Run Code Online (Sandbox Code Playgroud)

然后所有其他初始化内容和游戏循环开始以 sdl 事件切换然后(仍在游戏循环中):

//calculate everything if we are in playing gamestate
    if(id == MODE_PLAY)
    {
        rc = pthread_create(&t_engine, &attr, gameManager, (void *)t);
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
        //gameManager((void *)t);
    }

    //draw everything
    DrawGLScene();

if(id == MODE_PLAY)
    {
        rc = pthread_join(t_engine, &status);
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }
Run Code Online (Sandbox Code Playgroud)

游戏经理:

void *gameManager(void *t)
{
  //then lot of stuff
  //function ending like this
  pthread_exit((void*) t);
}
Run Code Online (Sandbox Code Playgroud)

ps:我正在使用 Windows 7,我的 ide 是代码块,我使用 gnu gcc 编译器 pps:我也尝试过互斥锁、sem 和其他东西,但没有任何真正的区别感谢您花时间帮助我(=

Mic*_*urr 5

这一点来自您对问题的解释:

然后所有其他初始化内容和游戏循环开始

让我相信执行pthread_create()/pthread_join()上面的代码片段是在循环中完成的。

如果是这种情况,请意识到重复创建/销毁线程是昂贵的。您需要考虑在您的gameManger对象中放置一个游戏循环,并将该循环与DrawGLScene()使用信号量、条件变量或线程障碍等执行的循环同步。除了使用线程终止作为同步技术之外的几乎任何东西。