• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

코드 실행속도가 너무 느립니다.

24.03.04 14:34 작성 조회수 81

1

강의를 보고 따라한 아래 코드의 실행속도가 강사님에 비해 너무나 느립니다. 실행환경의 문제인가요??

#include<iostream>
#include<thread>
#include<atomic>//나눌 수 없다는 뜻. 쓰레드에서 연산이 한번에 이루어지도록 함
#include<mutex>
#include<chrono>

using namespace std;

mutex mtx;

int main()
{
	//atomic<int> shared_memory(0);
	int shared_memory(0);

	auto count_func = [&]() {
		for (int i = 0; i < 1000; ++i)
		{
			//cout << shared_memory << endl;
			this_thread::sleep_for(chrono::milliseconds(1));
			//doSomething;
			
			//mtx.lock();
			//std::lock_guard lock(mtx);//unlock필요없음
			std::scoped_lock lock(mtx);
			shared_memory++;
			//shared_memory.fetch_add(1);
			//mtx.unlock();

			//shared memory의 값을 더할 떄의 과정
			//1.shared memory값을 cpu로 가져옴
			//2.1더함
			//3.sharedmemory에 결과 저장
			//값을 읽어들었을 때, 값이 바뀌면 더하기가 씹혀버림 => 잘못된 결과

			//해결법
			//1. atomic 사용
			//2. fetchadd
			//3. mutex lock

		}
	};

	thread t1 = thread(count_func);
	thread t2 = thread(count_func);

	t1.join();
	t2.join();
	std::cout << "After" << endl;
	std:: cout << shared_memory << endl;

	return 0;
}

답변 1

답변을 작성해보세요.

1

Soobak님의 프로필

Soobak

2024.03.05

안녕하세요, 질문&답변 도우미 Soobak 입니다.

 

실행 환경에 따라서 결과가 달라질 수는 있습니다.
한 번, 다른 프로그램, 프로세스 등이 자원을 많이 사용하고 있지는 않은지 확인해보세요.
추가적으로, 제가 질문자님께서 첨부해주신 코드를 통해 컴파일 및 프로그램을 실행했을 때는 강의와 동일하게 결과가 출력되네요.