std::thread

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

void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "function f1 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "function f2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

class foo
{
public:
    void bar()
    {
        for (int i = 0; i < 5; ++i) {
            std::cout << "bar::foo executing\n";
            ++n;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    int n = 0;
};

int main()
{
    int n = 0;
    foo f;
    std::thread t1(f1, n); // pass by value
    std::thread t2(&foo::bar, &f); // runs foo::bar() on object f
    std::thread t3(f2, std::ref(n)); // pass by reference

    t1.join();
    t2.join();
    t3.join();
    std::cout << "n is " << n << '\n';
    std::cout << "f.n (foo::n) is " << f.n << '\n';

    return 0;
}

Output:

bar::foo executing
function f1 executing
function f2 executing
function f2 executing
function f1 executing
bar::foo executing
function f2 executing
function f1 executing
bar::foo executing
bar::foo executing
function f1 executing
function f2 executing
function f2 executing
function f1 executing
bar::foo executing
n is 5
f.n (foo::n) is 5

std::mutex keep thread-safe

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

int n = 0;
std::mutex g_Mutex;
void f1()
{
    for (int i = 0; i < 5; ++i) {
        std::lock_guard<std::mutex> guarder(g_Mutex);
        ++n;
        std::cout << "function f1: " << n << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2()
{
    for (int i = 0; i < 5; ++i) {
        std::lock_guard<std::mutex> guarder(g_Mutex);
        ++n;
        std::cout << "function f2: " << n << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

int main()
{
    std::thread t1(f1);
    std::thread t2(f2);

    t1.join();
    t2.join();

    return 0;
}

The result will be like the following when there is no mutex.

function f1: function f2: 2
2
function f1: 3
function f2: 4
function f1: 5
function f2: 6
function f1: 7
function f2: 8
function f2: 9
function f1: 9

The mutex object make the threads safe.

function f1: 1
function f1: 2
function f2: 3
function f2: 4
function f2: 5
function f2: 6
function f2: 7
function f1: 8
function f1: 9
function f1: 10

std::mutex is a move-only type, it can’t be copied.

Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x