사용자 도구

사이트 도구


qt:thread

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
qt:thread [2014/02/19 06:34] changwooqt:thread [2014/10/09 21:24] (현재) – 바깥 편집 127.0.0.1
줄 9: 줄 9:
 각 Qt 어플리케이션은 글로벌하게 스레드 풀을 가지고 있다. 이를 이용해 재사용 가능한 스레드를 생성할 수 있다. 일례로 GUI 어플리케이션에서 어떤 일을 수행하면서도 다른 GUI 파트의 응답을 받을 수 있도록 해야 한다. 그렇게 하려면 어떤 일을 수행하는 코드는 반드시 스레드로 만들어야 응답성이 향상된다. 각 Qt 어플리케이션은 글로벌하게 스레드 풀을 가지고 있다. 이를 이용해 재사용 가능한 스레드를 생성할 수 있다. 일례로 GUI 어플리케이션에서 어떤 일을 수행하면서도 다른 GUI 파트의 응답을 받을 수 있도록 해야 한다. 그렇게 하려면 어떤 일을 수행하는 코드는 반드시 스레드로 만들어야 응답성이 향상된다.
  
 +===== 간단한 예제 =====
 +[[.:SignalsAndSlots]]에서 설명한 소스에 간단한 글로벌 스레드 풀에 ''Runnable'' 클래스를 동작시키는 예제를 작성하자.
 +
 +signal_emitter에 다음과 같이 소스를 추가한다.
 +<code cpp>
 +#include <QThreadPool>
 +#include <QRunnable>
 +
 +class ATask : public QRunnable
 +{
 +  void run()
 +  {
 +    for(int i = 0; i < 10; ++i) {
 +      std::cout << "counting in thread: " << i << '\n';
 +      QThread::sleep(1);
 +    }
 +  }
 +};
 +</code>
 +
 +launch() 함수는 다음과 같이 변경한다.
 +<code cpp>
 +void signal_emitter::launch()
 +{
 +  std::cout << "Hello, world!\n";
 +
 +  ATask *atask = new ATask();
 +  QThreadPool::globalInstance()->start(atask);
 +  //QThreadPool::globalInstance()->waitForDone();
 +  
 +  for(int i = 0; i < 10 ; ++i) {
 +    emit send(i);
 +    QThread::sleep(1);
 +  }
 +
 +  emit finished();
 +}
 +</code>
 +
 +이를 실행하면 다음과 같이 race가 발생한다.
 +<code>
 +Hello, world!
 +received: 0
 +counting in thread: 0
 +received: 1
 +counting in thread: 1
 +received: 2
 +counting in thread: 2
 +rceocuenitviendg:  in thread: 3
 +3
 +received: 4
 +counting in thread: 4
 +received: 5
 +counting in thread: 5
 +received: 6
 +counting in thread: 6
 +croeucnetiivnegd :i n thread: 7
 +7
 +croeucnetiivnegd :i n thread: 8
 +8
 +received: 9
 +counting in thread: 9
 +</code>
 +
 +주석을 해제하면
 +<code>
 +Hello, world!
 +counting in thread: 0
 +counting in thread: 1
 +counting in thread: 2
 +counting in thread: 3
 +counting in thread: 4
 +counting in thread: 5
 +counting in thread: 6
 +counting in thread: 7
 +counting in thread: 8
 +counting in thread: 9
 +received: 0
 +received: 1
 +received: 2
 +received: 3
 +received: 4
 +received: 5
 +received: 6
 +received: 7
 +received: 8
 +received: 9
 +</code>
 +
 +이 소스는 {{:qt:signal_slots_3.tar.gz|여기}}서 다운로드 받을 수 있다.
qt/thread.1392791697.txt.gz · 마지막으로 수정됨: 2014/10/09 21:23 (바깥 편집)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki