lundi 7 octobre 2019

Threads in C++ The interleaving pattern

In this program, I'm trying to print my username and then create two threads. I want each thread to print its thread id and go into a loop and display something periodically.

Here is the code I have

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <string>


void task(std::string threadNum)
{
    std::thread::id this_id = std::this_thread::get_id();
    std::cout << threadNum << " : " << this_id << std::endl;

    for(int i=0; i<1000; i++){
        if(i == 300 or i == 600 or i == 900){
            std::cout << threadNum << " has reached step: " << i << std::endl; 
        }
    }

}

int main()
{
    std::cout << "Your Username Is: " << getenv("USER") << std::endl;
    std::thread t1(task, "Thread 1");
    std::thread t2(task, "Thread 2");
    t1.join();
    t2.join();

}

and I get different outputs every single time I run the program, for example

Your Username Is: gansaikhanshur
Thread 2 : Thread 1 : 0x70000741e000
Thread 2 has reached step: 0x70000739b000300
Thread 1 has reached step: 300
Thread 2 has reached step: 600
Thread 2 has reached step: 900

Thread 1 has reached step: 600
Thread 1 has reached step: 900

Thread1 and Thread 2 does not show it's thread ID as it should. Why do I get different results all the time? and Is it possible for me to make thread 1 and thread 2 to display their correct thread ids?

Aucun commentaire:

Enregistrer un commentaire