Skip to content

Std::thread

Tip

  • sleep_for와 sleep_until을 사용하면 스레드를 일시 중지 시킬 수 있다.
    • sleep_for는 지정한 시간 동안(예 100밀리세컨드 동안만 정지), sleep_until은 지정 시간이까지(예 16시 10분까지 정지)
  • yield를 사용하여 자신(스레드)의 활동을 포기하고 다른 스레드에게 양보한다. std::this_thread::yield();

Example

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread

void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

Calling method of class

#include <thread>
// ...
void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>
// ...
void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Detach thread

#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n) 
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}

int main() 
{
  std::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1).detach();
  std::thread (pause_thread,2).detach();
  std::thread (pause_thread,3).detach();
  std::cout << "Done spawning threads.\n";

  std::cout << "(the main thread will now pause for 5 seconds)\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}

Thread group

Boost를 사용한 스레드 그룹은 아래와 같다.

#include "boost/thread.hpp"

class threadFunc
{
    int m_a;
public:
    threadFunc( int a )
    {
        m_a = a;
    }

    void operator()()  
    {  
        printf("[%d]일단 들어왔네!!! [%d]\n", boost::this_thread::get_id(), m_a );

        Sleep(5000);

        printf("[%d] 끝났네 [%d]\n", boost::this_thread::get_id(), m_a );
    }  
};

int main()
{
    boost::thread_group tg;

    tg.create_thread( threadFunc(1) );                        // 1번 스래드 생성 
    tg.add_thread(new boost::thread( threadFunc(2) ) );        // 2번 스래드 생성 
    tg.add_thread(new boost::thread( threadFunc(3) ) );        // 3번 스래드 생성 

    //모든 스래드가 종료 될때까지 대기 
    tg.join_all();

    return 0;
}

See also

Favorite site

Thread pool & Group

References


  1. Wchar_t_string_on_Linux_-_OS_X_and_Windows.pdf 

  2. C11_vs_Cpp11_vs_POSIX_Thread_API_comp_-_jacking75.pdf 

  3. Joinc_-_Thread_Pooling.pdf