0

I'm having trouble with a very basic program.

I want to do a monitoring function that can access two int who are constantly incremented in two other threads.

Here is my code and I compile with either gcc -std=c++14 Monitoring.cpp -pthread or gcc -std=c++11 Monitoring.cpp -pthread:

#include <thread>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <chrono>
#include <atomic>


void monitor_function(std::atomic<int>& a1,std::atomic<int>& a2)
{
    while(1){
        std::this_thread::sleep_for (std::chrono::milliseconds(1000));
        std::cout<<"a1 = "<<a1<<std::endl;
        std::cout<<"a2 = "<<a2<<std::endl;
    }
}

void thread_function_one(std::atomic<int>& a1)
{
    while (1){
        a1++;
    }
}

void thread_function_two(std::atomic<int>& a2)
{
    while (1){
        a2++;
    }
}

int main()
{

    std::atomic<int> a1(0);
    std::atomic<int> a2(0);
    std::thread t1(thread_function_one,a1);
    std::thread t2(thread_function_two,a2);
    std::thread t3(monitor_function,a1,a2);

    return 0;
}

Can you give me direction on how to use atomic variable inside threads ?

Thanks


EDIT :

I added protection and joined the threads :

#include <thread>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <chrono>
#include <atomic>


void monitor_function(std::atomic<int>& a1,std::atomic<int>& a2)
{
    while(1){
        std::this_thread::sleep_for (std::chrono::milliseconds(1000));
        std::cout<<"a1 = "<<a1<<std::endl;
        std::cout<<"a2 = "<<a2<<std::endl;
    }
}

void thread_function_one(std::atomic<int>& a1)
{
    while (1){
        a1++;
        if (a1 > 1000000){
            a1 = -1000000;
        }
    }
}

void thread_function_two(std::atomic<int>& a2)
{
    while (1){
        a2++;
        if (a2 > 1000000){
            a2 = -1000000;
        } 
    }
}

int main()
{

    std::atomic<int> a1(0);
    std::atomic<int> a2(0);
    auto t1 = std::thread(thread_function_one,a1);
    auto t2 = std::thread(thread_function_two,a2);
    auto t3 = std::thread(monitor_function,a1,a2);

    t1.join();
    t2.join();
    t3.join();
    return 0;
}

Still got lot of compilation error, can launch my program

EDIT 2 : added std::ref around a1 and a2 and it works, thanks.

    auto t1 = std::thread(thread_function_one,std::ref(a1));
    auto t2 = std::thread(thread_function_two,std::ref(a2));
    auto t3 = std::thread(monitor_function,std::ref(a1),std::ref(a2));
Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
falaxx
  • 1
  • 1

0 Answers0