【发布时间】:2016-12-29 17:50:22
【问题描述】:
当使用 printf (stdio.h) 时,"Start both threads\n" 和 "Enter a number\n" 混合在一起(类似于 "StEanterrt ba oth thnureaber\nads\n"),但这不会发生在 std::cout (iostream) 中。我怀疑这与 std::thread 有关,但我还是多线程编程的新手。
我真的不想使用 iostream,因为它让程序变得超级大!
我正在使用 mingw32 g++ 4.9.2,使用 g++ -o foreback foreback.cpp -O2 -std=c++11 编译。 (虽然我的电脑是64位的,但是我发现mingw-w64产生的程序大约是mingw32的两倍,所以我没有使用它。
//#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;
}
【问题讨论】:
-
为了记录,通常没有必要因为程序大小而弯曲变形。硬盘又大又快,程序被半延迟地映射到内存中,这样未使用的部分就不会延迟启动等。如果它运行得足够快,在可执行文件的大小上增加一个 MB 通常并不重要(我怀疑
iostream增加了那么多,尽管在 Windows 上,我不能 100% 确定它可以卸载到共享运行时库的多少)。 -
对于带有 stdio.h 的简单 hello world 程序,gnu gcc 产生 8KB,mingw32 产生 30KB,mingw-w64 产生 59KB。不过既然你说1MB的差别也无所谓,那我就不用担心了吧?
-
是的。即使是当今最慢、碎片最严重的旋转磁盘驱动器,其读取速度也只有几 MB/秒(如果没有碎片,则为几十或几百 MB/秒)。较小的计算机通常有大约 64 GB 的空间,其中大多数有 4-20 倍的空间;即使假设操作系统和其他应用程序使用 32 GB,使用 32 GB 可用空间中的 1 MB 通常并不重要,除非您实际上是在不同位置编译和安装程序的数百或数千个副本。 :-)
标签: c++ multithreading c++11