소프트웨어

[c++] thread 기본 구조, 모양

개발자_이훈규 2014. 1. 28. 11:36

1. 

thread에 함수 넣는 부분에 &를 붇이지 않아도 함수 이름이 갖고 있는 해당 메모리 주소로 인식된다는 말을 듣고 해보았지만 에러가 떠서 이것 저것 찾다가 그냥 예시를 찾았다.



2.

#include <cstdio>

#include <string>

#include <iostream>


#include <pthread.h>


void* print(void* data)

{

    std::cout << *((std::string*)data) << "\n";

    return NULL; // We could return data here if we wanted to

}


int main()

{

    std::string message = "Hello, pthreads!";

    pthread_t threadHandle;

    pthread_create(&threadHandle, NULL, &print, &message);

    // Wait for the thread to finish, then exit

    pthread_join(threadHandle, NULL);

    return 0;

}


A better alternative, if you're able to, is to use the new C++11 thread library. It's a simpler, RAII interface that uses templates so that you can pass any function to a thread, including class member functions (see this thread).


Then, the above exmaple simplifies to this:


#include <cstdio>

#include <string>

#include <iostream>


#include <thread>


void print(std::string message)

{

    std::cout << message << "\n";

}


int main()

{

    std::string message = "Hello, C++11 threads!";

    std::thread t(&print, message);

    t.join();

    return 0; 

(http://stackoverflow.com/questions/13128461/getting-error-when-using-pthread-create)