티스토리 뷰


쓰레드를 이용할일이 있어서 pthread로 쓰레드를 만들어봤다.

윈도우즈에서 pthread를 사용하는 방법은 이전 포스트에써 놨다.(http://idea-sketch.tistory.com/4)

pthread를 어떻게 쓰실지 잘 모르겠다는 분들은 여기를 참조하세요.

http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Beginning/PthreadApiReference


혹시나 필요하신 분들은 가져다 본이의 입맛에 맞게 고쳐쓰시면 되겠다.

준비물은 pthread.h이다.

CThread.h

#include <pthread.h>

 

class CThread

{

protected:

    pthread_t mThread;

bool threadRunFlag;

public:

    CThread ();

    virtual ~CThread ();

    virtual void run ()=0;

    static void* run_ (void*);

    void Start ();

    void Stop ();

bool IsRun();

};

 

CThread::CThread () 

{

this->threadRunFlag = false;

}

CThread::~CThread ()

{

if(this->IsRun())

{

this->Stop();

}

}

 

bool CThread::IsRun()

{

return this->threadRunFlag;

}

 

void* CThread::run_ (void* aThis) 

{

    CThread *pThis = (CThread *)aThis;

while( pThis->IsRun())

{

pThis->run();

}

return 0;

}

void CThread::Start ()

this->threadRunFlag = true;

    pthread_create (&mThread, NULL,&CThread::run_, (void*)this);

}

 

void CThread::Stop ()

{

this->threadRunFlag = false;

    pthread_join (mThread, NULL);

}

실제로 사용할때는 CThread를 상속받은후 run부분을 본인이 원하는 코드로 수정하면 된다.

다음은 테스트 코드이다. 

main.cpp
 

 

#include <windows.h>

#include "CThread.h" 

#include <stdio.h>

 

 

class ThreadTest:public CThread

{

private:

    int num;

public:

    ThreadTest () { num = 0; }

    ThreadTest (int num) { this->num = num; }

    virtual void run ()

    {

        printf ("%d", num);

    }

};

 

int main ()

{

    ThreadTest test1(3);

    ThreadTest test2(4);

    test1.Start ();

    test2.Start ();

Sleep(1000);

    test2.Stop ();

    test1.Stop ();

}

결과화면이다.  3만 보여주는 쓰레드하나와 4만보여주는 쓰레드하나를 동작시켜서 나온 결과화면이다.




누군가에게는 작은도움이 되었기를 바라면서 오늘의 포스팅 끝~

댓글