私は最近、マルチスレッドの周りで頭を抱えて、どのように動作するかを理解しようとしています。私はここにいくつかのサンプルコードを持っていますが、私は出力がそれがどのようなものなのか理解できません。スレッドの実行順序は何ですか?
例コード:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
std::mutex mtx;
int global_counter = 0;
std::mutex counter_mutex;
void five_thread_fn(){
for(int i = 0; i<5; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from five_thread" << endl;
counter_mutex.unlock();
// std::this_thread::sleep_for(std::chrono::seconds(5));
}
//When this thread finishes we wait for it to join
}
void ten_thread_fn(){
for(int i = 0; i<10; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from ten_thread" << endl;
counter_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
//When this thread finishes we wait for it to join
}
int main(int argc, char *argv[]) {
std::cout << "starting thread ten..." << std::endl;
std::thread ten_thread(ten_thread_fn);
std::cout << "Starting thread five..." << endl;
std::thread five_thread(five_thread_fn);
five_thread.join();
std::cout << "Five Thread is done." << std::endl;
ten_thread.join();
std::cout << "Ten Thread is done." << std::endl;
// std::cin.ignore();
return 0;
}
私は、スレッドでの時間遅延をコメントアウトし、ここで私の出力でいます
Starting thread ten...
Starting thread five...
Updated from five_thread
Updated from ten_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Five Thread is done.
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Ten Thread is done.
「ten_threadから更新」ん、なぜ今、私は疑問に思って後に表示されます"five_threadから更新されました"の最初の行?主な機能には
私は
five_thread.join();
を行うfive_threadがその実行を完了するまで、メインスレッドを中断しないようにしていますか?
私が理解するように、five_thread.join()の後の行が(順番に)実行されるのはfive_threadの終了後です。では、ten_threadはどうやって呼び出されていますか?
main()内のコード行は連続して実行されていませんか?私の理解へ
'ten_thread'はメインスレッドではありません。そのプログラムには** 3 **スレッドがあり、唯一のスレッドはメインスレッドです。 'five_thread'と' ten_thread'はお互いに同時に実行されます。 – Galik