lundi 22 août 2016

printf calls messed up with std::thread but std::cout are fine

When printf (stdio.h) is used, "Start both threads\n" and "Enter a number\n" mixed together (something like "StEanterrt b a oth thnureaber\nads\n"), but this does not happen in std::cout (iostream). I suspect this has something to do with std::thread, but I am still new with multi-threading programming.

I really don't want to use iostream because it makes the program super large!

I am using mingw32 g++ 4.9.2, compile with g++ -o foreback foreback.cpp -O2 -std=c++11. (Although my computer is 64-bits, but I find out that mingw-w64 produces program about twice the size by mingw32, so I didn't use it).

//#define IOS
#ifdef IOS
#include <iostream>
#endif
#include <stdio.h>
#include <thread>
#include <atomic>
#include <windows.h> // for Sleep()

std::atomic<int> atom(1);

void foreground() {
    int c = 1;
    while (c) {
#ifdef IOS
        std::cout << "Enter a number: ";
        std::cin >> c;
#else
        printf("Enter a number: ");
        scanf("%d", &c);
#endif
        atom.store(c, std::memory_order_relaxed);
    }
}

void background() {
    FILE *out = fopen("foreback.txt", "w");
    int c = 1;
    while (c) {
        fprintf(out, "%d", c);
        c = atom.load(std::memory_order_relaxed);
        Sleep(500);
    }
    fclose(out);
}

int main() {
    std::thread f(foreground), b(background);
#ifdef IOS
    std::cout << "Start both threads.\n";
#else
    printf("Start both threads.\n");
#endif
    f.join();
    b.join();
#ifdef IOS
    std::cout << "End of both threads.\n";
#else
    printf("End of both threads.\n");
#endif
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire