无法在正确的地方加入线程

问题描述 投票:0回答:0

在我的游戏中有两个(与这个问题相关的)线程(都是可连接的),一个是玩家,一个是射击。创建线程播放器时,会调用启动例程函数,在该函数中创建拍摄线程。在那个函数中,有一个 while 循环,用户可以在其中决定地图或镜头的移动方向,如果是镜头,我会创建镜头线程,玩家应该在镜头处于活动状态时移动,而只有一次镜头一次可以活动。我的问题是,当我在创建镜头线程的镜头上使用

pthread_join
功能(一次执行一个镜头)时,播放器保持冻结状态。我的问题是,在不干扰玩家移动的情况下使用
pthread_join
的正确位置在哪里。我已经尝试在shot线程的启动例程函数中使用join,在主程序(main)中,没有一个能正常工作。 (代码示例仅作为程序中发生的情况的近似表示)。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_t player_tid;
pthread_t shot_tid;
int life_points = 100;

typedef struct
{
    unsigned char x_;
    unsigned char y_;
    unsigned char type_;
    unsigned char index_;
} parametars;

void *placeShot(parametars *params)
{
// TODO start: find if shot hit an alien, remove shot and alien if so. // Hint: I have already implemented that, works fine.
    printf("Shot coordinates: %d, %d", params->x_, params->y_);
    free(params);
// TODO end;
    return NULL;
}

void *playerLogic()
{
    int c;
    
    while (life_points > 0)
    {
        char shot = 0;
        c = getchar();
        switch (c)
        {
        case ' ':
            shot = 1;
            break;
        default:
            break;
        }
        if (c == 'q')
        {
            life_points = 0;
            continue;
        }
// TODO start: spawn the shot and make sure to wait until the last shot is //finished
        parametars *params;
        if (shot)
        {
            params = malloc(sizeof(parametars));
            params->x_ = 3;
            params->y_ = 2;
            if (pthread_create(&shot_tid, NULL, (void *(*)(void *)) & placeShot, params) != 0)
            {
                printf("Failed to create shot thread");
            }
        }
// TODO end
    }
   
    return NULL;
}

int main()
{
    // TODO create a player thread with already provided resources
    if (pthread_create(&player_tid, NULL, (void *(*)(void *)) & playerLogic, NULL) != 0)
        printf("Failed to create player thread");

    if (pthread_join(player_tid, NULL) != 0)
        printf("Failed to join player thread");

    return 0;
}
c multithreading pthreads pthread-join
© www.soinside.com 2019 - 2024. All rights reserved.