Running time error with thread.

Issue #292 invalid
Ngoc Phuong Chau created an issue

My testing is that we have a program and I want to stop after 25s. Instead of using main thread, I want to use another thread in the same rank to count the time. After 25s, the thread will change running value to “false”. Hence, main thread will stop, too.

When I run sample code as belows, and it worked with g++ compiler.

bool running = true;
int num_time =25;
thread t_time( [&]() {
cout<<"sleep"<<endl;
    std::this_thread::sleep_for( std::chrono::seconds(num_time) ) ; 
running = false;
});

while(running)
{
    int t=0;
t++;
};

t_time.join();
cout<<"done!"<<endl;

After that, I copy to between upcxx::initial() and upcxx::finalize(). It did not worked. I waited around 30 minutes but the program did not stop. With c++, after 25s, the program stopped.

Could you please suggest any solution for this situation? If I want to use more threads, this is possible with upc++?

Thank you so much.

Comments (6)

  1. Dan Bonachea

    Hi @Ngoc Phuong Chau -

    Your experiment works fine on my Linux system using g++ 9.2.0 and either the smp or ibv network backends with the following program:

    $ cat issue292.cpp 
    #include <upcxx/upcxx.hpp>
    #include <thread>
    
    using namespace std;
    
    int main() {
    
    upcxx::init();
    
    bool running = true;
    int num_time =5;
    thread t_time( [&]() {
    cout<<"sleep"<<endl;
        std::this_thread::sleep_for( std::chrono::seconds(num_time) ) ; 
    running = false;
    });
    
    while(running)
    {
        int t=0;
    t++;
    };
    
    t_time.join();
    cout<<"done!"<<endl;
    
    upcxx::finalize();
    }
    
    $ upcxx -threadmode=par -g issue292.cpp && upcxx-run -np 1 a.out
    sleep
    done!
    

    Can you please provide more details about your system, compiler, UPC++ version, compile line and a complete example code?

    At this point my best guess is the upcxx link step may be pulling in a different thread library on your system and causing some kind of problem. Please also provide verbose -v compile output for your "working" and "non-working" compilations.

  2. Dan Bonachea

    @Ngoc Phuong Chau :

    The problem appears to be that your C++ code is violating the C++ memory model - there is a data race on the variable running, which the spec prohibits. The C++ optimizer is within its rights to optimize away the reference in the loop, and the result is a hang.

    The simplest solution is to promote your running variable to be atomic:

    std::atomic<bool> running(true);
    

    when I made this change everything works in opt mode

  3. Log in to comment