다음 튜토리얼을 통해 읽었습니다 : C++ Multithreading Tutorial. 10 개의 고유 스레드를 생성하고 스레드 번호가있는 문자열을 인쇄하는 자습서의 코드를 컴파일했습니다. 여기뮤텍스 & 스레드 : 설명
코드가 링크를 열고 싶어하지 않는 사람들을위한 모습입니다 :
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
내가 코드를 실행하면 컴파일 및 출력이 가지 무작위입니다. 각 스레드를 시작하지만 순서대로 시작하지는 않습니다.
std :: mutex에서 C++ 참조를 읽었으며 필자가 필요로하는 것처럼 들립니다.
그래서 누군가가 나에게 같은 표준 코드를 구현하는 방법에 대한 빠른 정리를 줄 수 있는지 궁금 해서요. 스레드가 동일한 공유 리소스를 사용하지 않도록 보장하고 순서대로 실행되도록합니다. .
당신은 그들이 순서대로 시작하지 않았다고 생각합니까? 이 코드는 매우 명확하게 순서대로 실행합니다. –
[Mutex example/tutorial?]의 가능한 복제본 (http : // stackoverflow.com/questions/4989451/mutex-example-tutorial) – TemporalWolf
문제의'std :: mutex'는 어디에 있나요? 또한'std :: mutex'는 엄격한 실행 순서를 보장하지 않습니다. –