Threads in C++11

Maybe I need threads in my rig control program, so here is a simple test.

//======================
// SprigThreadTest.cpp
//======================
#include <iostream>
#include <thread>

void f()
{
    std::cout << "void f()" << std::endl;
}

void g()
{
    std::cout << "void g()" << std::endl;
}

int main(int argc, char **argv)
{
    std::thread t1(f);
    std::thread t2(g);
    t1.join();
    t2.join();
}

Let’s see what happens.

% ./SprigThreadTest 
void g()void f()

% ./SprigThreadTest 
void f()
void g()

% ./SprigThreadTest 
void f()
void g()

% ./SprigThreadTest 
void f()
void g()

% ./SprigThreadTest 
void g()void f()

% ./SprigThreadTest 
void f()
void g()

% ./SprigThreadTest 
void f()
void g()

Looks reasonable? Of course, cout is not thread safe, so we may have interleaved characters.

void f()
{
	for(int i=0;i<10;i++) {
		std::cout << "abcdefghij" << std::endl;
	}
}

void g()
{
	for(int i=0;i<10;i++) {
		std::cout << "0123456789" << std::endl;
	}
}
% ./SprigThreadTest
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij

% ./SprigThreadTest
0123456789abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij

0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789

Properties for Sprigmm025 _081

Leave a Reply

Your email address will not be published. Required fields are marked *