Create a new Thread

Hello. I am trying to create a thread so as to manage some delay inside a process. I tried with Sleep and Thread, but it freezes my project because it blocks the main thread. In C# it is named Coroutine. I asked myself if there is something more or less similar in C++. I found some examples on the Web so as to create a new thread, but I cannot achieve my goal. Any help will be appreciated. Maybe just a clean example. Thank you ++

I use Windows 10 and Visual Studio 2019
Last edited on
Coroutine support was added in C++20.
https://en.cppreference.com/w/cpp/coroutine

That being said, you don't need coroutines to achieve a particular functionality, it just simplifies things.

Show us the code that you say is causing blocking in main. join() is a blocking call, so if you make a single thread and then immediately wait for it to join, it doesn't do much good.
Can you give more information about what you're trying to do? A coroutine and a thread are two very different things.
Geckoo, there are multiple different ways to achieve such behavior.
See, for example: https://stackoverflow.com/questions/9094422/how-to-check-if-a-stdthread-is-still-running

Here's one way to keep track of the thread's state, using atomic variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <functional>
#include <atomic>
#include <chrono>
#include <thread>

void sleep(int milliseconds)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

void thread_func(std::atomic<bool>& thread_finished)
{
    sleep(5000);
    
    thread_finished = true;
}

int main()
{
    std::atomic<bool> thread_finished { false };
    std::thread thread(thread_func, std::ref(thread_finished));
    
    while (!thread_finished)
    {
        std::cout << "Doing other stuff while waiting for thread to exit...\n";
        sleep(100);
    }

    thread.join();
    
    std::cout << "Finished!\n";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for (int i = 0; i < noEnemies; i++)
        {   // check for collisions with enemies
            CollisionDistances cd = enemies[i]->CharacterCollides(character);

            if (cd.bottom > 0.1f) // check collision
            {
                Enemy* enemy = enemies[i];

                for (int k = i; k < noEnemies - 1; k++)
               {
                    enemies[k] = enemies[k + 1];
                   // now enemy is dead
                   enemy->deadNow(); // start fading
                   character->Jump(false); // bouncing FX
                   // need to delay an object destruction here calling waitMe()
                   // clean array
                   enemies[noEnemies - 1] = NULL;
                   noEnemies--;
            }
        }


1
2
3
4
5
void Engine::waitMe(GameObjectBase* enemy)
{
    Sleep(1000);
    RemoveGameObject(enemy);
}


Ok. I will try to be clear. When an enemy object is killed by the player, I fade it calling another function which manages GameObject. So I want to delay the destruction because the sprite is fading. Using Sleep, I freezes the main process.

However maybe it could be more interesting for me to destroy the GameObject itself when transparency is near to zero. I tried, but delete(this) kills the main thread too.

No sorry, it's not clear. Sorry - forgive me :/
Last edited on
This is tricky. Coroutines would certainly be the correct solution, but your design needs to account for them first. They're not something you can just drop into your code and expect it to work.

Here's how I'd do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Game{
    std::map<uintptr_t, std::unique_ptr<Actor>> actors;
    std::set<uintptr_t> release;
    
    void update();
    void new_actor(std::unique_ptr<Actor> &&actor){
        auto p = (uintptr_t)actor.get();
        this->actors[p] = std::move(actor);
    }
    void release_actor(Actor &actor){
        this->release.insert((uintptr_t)&actor);
    }
};

void Game::update(){
    for (auto &kv : this->actors)
        kv.second->update();
    
    for (auto p : this->release)
        this->actors.erase(p);
    this->release.clear();
}

class Actor{
protected:
    int health;
    Game *game;

    virtual void logic() = 0;
public:
    void update(){
        //Do coroutine stuff. The coroutine eventually calls the logic()
        //override.
    }
    //Yields the coroutine until the next frame.
    void wait_for_next_frame();
    void gradual_fadeout(double length){
        auto start_time = this->game->get_time();
        auto end_time = start_time + length;
        while (true){
            auto now = this->game->get_time();
            if (now >= end_time){
                this->opacity = 0;
                return;
            }
            //1 = fully opaque
            this->opacity = (now - start_time) / (end_time - start_time);
            this->wait_for_next_frame();
        }
    }
};

class SmallShip : public Actor{
    void logic(){
        while (this->health > 0)
            this->wait_for_next_frame();
        this->gradual_fadeout(1);
        this->game->release_actor(*this);
    }
};


Boost has a good stackful coroutine implementation.
Last edited on
https://stackoverflow.com/questions/1372967/how-do-you-use-createthread-for-functions-which-are-class-members

I found a link with an interesting alternative so as to delay a function. This is exactly what I searched. Maybe it is not the best way, but it works well as expected. I share with you the link - it could be useful for other members. However thank you for your help and your kind and relevant advices ++
A better way is using the C++ thread:

http://www.cplusplus.com/reference/thread/thread/?kw=thread


I fade it calling another function which manages GameObject.
I would do the whole fading inside the thread. Maybe marking the object as 'fadng' and then as 'dead'.

Just remember to protect (with mutexes) the shared variables across the threads.
There's multiple ways to skin this cat, but personally I would just handle all of this within the update logic within each frame/timestep of your game. If an enemy is dying or whatever, then part of its death animation includes fading away, and the state for this is handled somewhere and updated each frame, still synchronous with everything else.
Thank you for your advice. When I was searching some explanations on the Web, I read the link which you shared with me coder777, but in my case it freezes my main thread instead to create something new in parallel.
Ganado - as you said, there are many ways to reach my goal, but your idea is really relevant. However it seems that I have to rewrite some parts of the code. Thanks ++
I would strongly advice against using threads for this. You really don't want game logic running completely independently of the main thread. It's going to bite you in the ass eventually. It's better to make the change now while the code is still manageable. You don't have to do it with coroutines like I did, it can also be done with state machines. But trust me, you want this to run in the main thread.
I would like to avoid complex threads independently. I would like to do this in the main thread, but trying to reach my goal, I have not found any efficient way. I have to take a look at the state machine. Thanks ++
Topic archived. No new replies allowed.