Brini
Brini

Reputation: 47

Running threads from within classes

I'm trying to perform two operations at once, a loop in the program's main method that prints out Tick from main and another loop in a class that prints out Tick from ConnectionManager.

This specific piece of code I'm running here is taken from one of the questions asked here.

The main.cpp file:

#include <Windows.h> // printf, Sleep
#include <thread> // thread

// Include Connection Manager
#include "ConnectionManager.h"

int main() {
    ConnectionManager _CM;

    while (1) {
        printf("Tick from main");
        Sleep(1500);
    }
}

ConnectionManager.h

#pragma once
class ConnectionManager
{
private:
    void LoopForData();
public:
    ConnectionManager();
};

ConnectionManager.cpp

#include "ConnectionManager.h"

#pragma once
#include <Windows.h>
#include <thread>

void ConnectionManager::LoopForData() {
    while (1) {
        printf("Tick from connection manager\n");
        Sleep(1500);
    }
}

ConnectionManager::ConnectionManager()
{
    std::thread tobj(&ConnectionManager::LoopForData, this);
}

The expected behaviour is that both loops run simultaneously, however the output I'm getting on the console is only from LoopForData function, and I get this error screen: https://i.sstatic.net/BCQRn.jpg

What could I be missing?

Upvotes: 1

Views: 98

Answers (1)

Tofu
Tofu

Reputation: 3613

This should work fine.

#include <iostream>
#include <thread>
#include <chrono>

//ConnectionManager.h
class ConnectionManager
{
private:
    std::thread tobj;
public:

    ConnectionManager();
    ~ConnectionManager();
private:
    void LoopForData();
};
//ConnectionManager.cpp
#include "ConnectionManager.h"

void ConnectionManager::LoopForData(){
    while (1) {
        std::cout << "Tick from connection manager" << std::endl;
        std::this_thread::sleep_for (std::chrono::milliseconds(1500));
    }
}
ConnectionManager::~ConnectionManager(){
    if(tobj.joinable()){
        tobj.join();
    }
}
ConnectionManager::ConnectionManager() : tobj(&ConnectionManager::LoopForData, this){

}
//main.cpp

#include "ConnectionManager.h"
int main() {
    ConnectionManager _CM;

    while (1) {
        std::cout << "Tick from main" << std::endl;
        std::this_thread::sleep_for (std::chrono::seconds(1));
    }
}

I think your main issue had to do with tobj going out of scope when the constructor exits. Also you can use the c++ standard sleep instead of Sleep from Windows.

Upvotes: 3

Related Questions