私は C++ プログラミングに戻るので、新しい C++ 標準を習得するために多くのことを試みています。私が提供したコードが非常に悪いことを知っています。私はそれを修正する方法を知っていると思います。
コード:
#include <iostream>
#include <thread>
using namespace std;
void apple (string const& x)
{
cout << "aaa" << endl;
}
void orange()
{
//string s = "hello";
thread t(apple,"hello");
t.detach();
}
int main() {
orange();
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
1 種類の出力:
!!!Hello World!!!
aaa
aaa
コードから、「aaa」を一度出力する必要があることがわかります。私の質問は、出力に「aaa」が 2 つある理由です。この問題の原因は何ですか?
どうもありがとう
編集:システム情報を追加:
Using built-in specs.
COLLECT_GCC=/usr/bin/g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.6.3/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.6.3 20120306 (Red Hat 4.6.3-2) (GCC)
その他の出力:
タイプ A:
!!!Hello World!!!
aaaaaa
タイプB:
!!!Hello World!!!
タイプC:
!!!Hello World!!!
aaaaaa
タイプ D:
!!!Hello World!!!
aaa
<empty line>
編集:@マークの答えに従って。これは未定義の動作です。
「sleep(1);」を追加しました。メインリターン前。1 種類の出力しか得られません。未定義の場合、なぜ他のタイプの出力が表示されないのですか?
出力:
!!!Hello World!!!
aaa